Jquery Show Input Text Based On Input Value

2019-02-25 16:34发布

I facing problem with my jquery, on showing input text based on input value. Here is the JS fiddle demo :

http://jsfiddle.net/Ltapp/364/

When I try to input @hotmail, the input box will show. But when I want to type some text in the #hotm input box, it will hide again.

JS code :

$(window).load(function(){
var myString = '@hotmail';
$('#hotm').hide();

$("input").keyup(function () {
var value = $(this).val();
    if($(this).val().match(myString)) {
        $('#hotm').show();
    } else {
        $('#hotm').hide(); 
    }
});

});

5条回答
ゆ 、 Hurt°
2楼-- · 2019-02-25 16:54

it's because the new box also = "input"; if you give the hotmail textbox it's own id, it won't hide

<input id="hotmail" type="text"/>

and then

$("#hotmail").keyup(function () {...});
查看更多
一纸荒年 Trace。
3楼-- · 2019-02-25 17:02

use this for your if part :

if($(this).val().match($(this).val().substr(0,strlen($(this).val())))
查看更多
狗以群分
4楼-- · 2019-02-25 17:03

You're affecting all inputs. Either give each one a unique ID / Class or use the jQuery $(this) method.

See JSFiddle Here:

http://jsfiddle.net/Ltapp/366/

<input type="text" id="firstinput"/>
<p id="secondinput"><input type="text"/></p>


var myString = '@hotmail';
$('#secondinput').hide();

$("#firstinput").keyup(function () {
var value = $(this).val();
    if($(this).val().match(myString)) {
        $('#secondinput').show();
    } else {
        $('#secondinput').hide(); 
    }
});
查看更多
你好瞎i
5楼-- · 2019-02-25 17:07

It's because your selector $("input") affects both input elements. I have updated it to the $("input:first") selector instead. JsFiddle here

    $("input:first").keyup(function () {
    var value = $(this).val();
    if(value.match(myString)) {
        $('#hotm').show();
    } else {
        $('#hotm').hide(); 
    }
});
查看更多
迷人小祖宗
6楼-- · 2019-02-25 17:21

As many has said, you are binding the event on all the inputs I did a little change:

$(function(){
    var myString = /@hotmail/ig;
    $("#check").bind('keyup checkvalue', function() {
        $('#hotm')[myString.test(this.value) ? 'show' : 'hide']();
    }).trigger('checkvalue');
});

using regex if you are using @HoTmAil it will also hit on that, and also added a custom event checkvalue to see if #hotm should be visible on for example a postback on the form you might be using.


demo: http://jsfiddle.net/voigtan/xjwvT/1/

查看更多
登录 后发表回答