开发者

jquery array .val()

开发者 https://www.devze.com 2023-01-30 03:20 出处:网络
I have this code below... if (x == 0) { $(\"#scenariotitle\").val(\'\'); $(\"#scenariosuffix\").val(\'\');

I have this code below...

if (x == 0) {
            $("#scenariotitle").val('');
            $("#scenariosuffix").val('');
}

...which works fine. However, that list will grow to about 5 more jquery selects.

Is there a way to store them into an array and then use the .val('') function on all the elements in the array? If that is possible, will it be more ef开发者_JAVA技巧ficient? Should I just stick to listing them out individually if the list is not greater than 10?

EDIT: I have decided to use this...

$("#scenariotitle, #scenariosuffix, #scenariosuffix, #scenariosuffix").val("");

...which is why I accepted the answer below. However, there is a very good discussion in the comments, and other answers provided, on how to properly use a jquery array selector.


You can concat multiple selectors into one statement:

selector #1, selector #2, selector #3

$("#scenariotitle, #scenariosuffix, #scenariosuffix, #scenariosuffix").val("");

Of course you could use an array but it's quite pointless in this case:

var selectors = [ "selector #1", "selector #2", "selector #n" ];
for (var i=0; i<selectors.length; i++) {
    $(selectors[i]).val("");
}


You can store the selectors in an array, then combine them for use if you wanted, like this:

var selectors = ["#scenariotitle", "#scenariosuffix"];
$(selectors.join(", ")).val("");

This takes the array then using .join() turns it into a multiple selector (comma separated) to grab all the elements at once.


Crozin has already mentioned a good way to reset based on the IDs so I won't repeat his solution. Another option that you can consider would be using a class selector.

If your HTML looked like this:

<input type='text' name='scenariotitle' class='resettable' />
<input type='text' name='scenariosuffix' class='resettable' />
<input type='text' name='scenariosomething' class='resettable' />
<input type='text' name='scenarioagain' class='resettable' />

Then you can have this:

$(".resettable").val("");


Adding an extra case to what Crozin wrote (which is all correct). If you need to accrue the list over time, just add them to a jQuery object.

var blankList = $();

...

blankList = blankList.add('#scenarioTitle');
...
blankList = blankList.add('#scenarioSuffix, #secondSuffix');
...

if (x == 0) {
    blankList.val('');
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号