JQuery: check if val () has a specific value or not when submitting a form

I am trying to check whether val () has a specific value or not inside the form, if it is deleting the contents / preventing the form from being submitted depending on whether both fields (stringOne and stringTwo) are filled. There is default text for each input field, the first of which is Namn, telefonnr, sökord and the second Område, plats, ort. If the user fills in only the first field, the second should be cleared before submitting the form line and vice versa. Also -

// "This" refers to the form 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 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.

+3
source share
2 answers

jQuery, val(), .

$('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 submit button
if ( (!$strOne.val() || $strOne.val() == "Namn, telefonnr, sökord") && (!$strTwo.val() || $strTwo.val() == "Område, plats, ort" ) {
    return false; // If nothing 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("");
    }
}
+2

, - :

if ($('#my_text_field').val() == "Clear Me") {
    $('#my_text_field').val("");

$('#my_text_field[value="Clear Me"]').val("");

$('#my_text_field[value="Clear Me"]').val("").change();

The.change() , $('# my_text_field [value = "Clear Me" ]') #my_text_field

+1

Source: https://habr.com/ru/post/1747862/


All Articles