jQuery: Check whether val() has a specific value or not upon form submit
I'm trying to check whether val() has a specific value or not inside a form, if so deleting the contents / preventing the form being submitted depe开发者_JAVA百科nding on if both fields are filled in (stringOne and stringTwo). There's a default text for each input field, the first being "Namn, telefonnr, sökord" and the second "Område, plats, ort". If a user only fills in the first field the second must be cleared before the form string is passed on and vice versa. Like so -
// "This" refers to the form's submit button
if (($(this).siblings('input.stringOne').val("Namn, telefonnr, sökord")) && ($(this).siblings('input.stringTwo').val("Område, plats, ort"))) {
return false; // If nothing's filled in, then do not submit
} else {
// If either field is not filled in, clear it
if ($(this).siblings('input.stringOne').val("Namn, telefonnr, sökord")) {
$(this).siblings('input.stringOne').val() == '';
}
if ($(this).siblings('input.stringTwo').val("Område, plats, ort")) {
$(this).siblings('input.stringTwo').val() == '';
}
}
jQuery version 1.2.6.
in jQuery, when you place a value inside val()
, you are setting the value.
$('myElement').val() // returns the value
$('myElement').val('some string') // sets the value
.val()
- http://api.jquery.com/val/
var $strOne = $(this).siblings('input.stringOne');
var $strTwo = $(this).siblings('input.stringTwo');
// "This" refers to the form's submit button
if ( (!$strOne.val() || $strOne.val() == "Namn, telefonnr, sökord") && (!$strTwo.val() || $strTwo.val() == "Område, plats, ort" ) {
return false; // If nothing's filled in, then do not submit
} else {
// If either field is not filled in, clear it
if ($strOne.val() == "Namn, telefonnr, sökord") {
$strOne.val("");
}
if ($strTwo.val() == "Område, plats, ort" ) {
$strTwo.val("");
}
}
I hope this will be useful to someone:
This code
if ($('#my_text_field').val() == "Clear Me") {
$('#my_text_field').val("");
Can be written
$('#my_text_field[value="Clear Me"]').val("");
Even better
$('#my_text_field[value="Clear Me"]').val("").change();
The .change() has the effect that $('#my_text_field[value="Clear Me"]') will not match #my_text_field after its value has changed
精彩评论