I have a small subset of fields that need blanked on a page (so I can't just run something using 开发者_如何学JAVA:input).
At the moment the code is something like this..
$('#txt1').val('');
$('#txt2').val('');
$('#txt3').val('');
Is it more efficient to chain them or is there some other method entirely I could use?
You can do:
$('#txt1, #txt2, #txt3').val('');
Or:
$('#txt1, #txt2, #txt3').empty();
As can be seen, you can combine multiple selectors by separating them with a comma.
Alternatively you can apply a class to fields you want to clear the text of and use the class in the selector like this:
$('.empty').empty();
where your fiels should look like:
<input class='empty' name="name1" />
<input class='empty' name="name2" />
<input class='empty' name="name3" />
You can select them all at once:
$('#txt1, #txt2, #txt3').val('');
This won't make a significant difference, but probably will make a small improvement. The biggest improvement is in making your code less repetitive and therefore easier to follow.
Edit: In fact, this makes the selection significantly slower. This is because selections by a single ID are very fast. document.getElementById
is quicker than document.querySelectorAll
. Stick with what you have.
You could try adding a class to each...
HTML
<input class='blankable' type=... />
JavaScript
$('.blankable').val('');
Well i would do it with one line and null, but i guess its however you prefer it:
<input value="foo" id="txt1" />
<input value="foo" id="txt2" />
<input value="foo" id="txt3" />
<script type='text/javascript' src='http://code.jquery.com/jquery-latest.min.js'></script>
<script>
$(document).ready(function(){
$('#txt1, #txt2, #txt3').val(null);
});
</script>
Be aware that setting .val('')
will not work for all types of :input
elements.
I use the following function which may not be complete but covers all the scenarios my application currently encounters.
function clearForm($container) {
$(':input', $container).each(function() {
$(this).removeClass('input-validation-error');
if (!$(this).attr('readonly')) {
var type = this.type;
if (type == 'text' || type == 'file')
this.value = "";
else if (this.tagName.toLowerCase() == 'select')
this.selectedIndex = 0;
// checkboxes need to have their checked state cleared
// but should *not* have their 'value' changed
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
}
});
}
jQuery(':input').val('');
should select all your inputs and clear the value. I do not know however if <select>
and <textarea>
need special attention. Also, you might need to exclude invisible inputs if you have <input type="hidden">
. In that case, consider:
jQuery('[type!="hidden"]:input').val('');
EDIT
Just read that I missed something. If you are selecting from a subset, select the subset first.
jQuery('#subset :input').val('');
精彩评论