简体   繁体   中英

How to change input element's visibility through jquery?

For tag the below code is working fine, but for <input> isn't. Can you guide me how to solve it?

html:

<span id="toValue">AND</span>
<input id="toValue">

css:

#toValue {
    visibility: hidden;
}

js:

$('#toValue').css("visibility", "visible");

Don't repeat the same id in the same page. Change it to a class:

.toValue {
    visibility: hidden;
}

Html:

<span class="toValue">AND</span>
<input class="toValue">

Then:

$('.toValue').css("visibility", "visible");

Demo .

Or use different ids to each element:

<span class="toValue" id="mySpan">AND</span>
<input class="toValue" id="myInput">

Then:

$('#mySpan, #myInput').css("visibility", "visible");

Demo

Your markup is invalid: two elements with the same id . Use class instead:

HTML

<span class="toValue">AND</span>
<input class="toValue">

CSS:

.toValue {
  visibility: hidden;
}

ids must be unique for elements. the first element with that particular id will always be updated and the other discarded so either use the "class" attribute or change the ids

Same ids to multiple elements in a single page makes an invalid markup and that is hard to work when you try using js with those elements.

For tag the below code is working fine, but for <input> isn't.

It is because:
Browser stops the lookup at first element found and don't go next to look for another one.
NOTE:- If you try check the length of your selector it would always return 1.

Solution to this is that you change the id to class attribute and the css as well:

.toValue {
    visibility: hidden;
}

and

<span class="toValue">AND</span>
<input class="toValue">

in js:

$('.toValue').css("visibility", "visible");

Id must be unique, Either you can also use class if you want to use common selector, here is demo of simple show and hide of your elements

 function func1(){ $("#spanValue").hide(); $("#inputValue").hide(); } function func2(){ $("#spanValue").show(); $("#inputValue").show(); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span id="spanValue">AND</span> <input id="inputValue" type="text"> <input type="button" onClick="func1();" value="Hide"> <input type="button" onClick="func2();" value="Show"> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM