简体   繁体   中英

Foreach if statement loop through form javascript

Is it possible and to make loop to check each input text field in html form? For example, form has 8 input fields with predefined 0 value.

Form code:

<form method="post" action="" id="form"> 

<input type='text' name="One"  id="one" value='0'>
<input type='text' name="Two"  id="two" value='0'>
<input type='text' name="Three"  id="three" value='0'>
<input type='text' name="Four"  id="four" value='0'>
<input type='text' name="Five"  id="five" value='0'>
<input type='text' name="Six"  id="six" value='0'>
<input type='text' name="Seven"  id="seven" value='0'>
<input type='text' name="Eight"  id="eight" value='0'>

</form>

When user changes some of them to any other numeric value greater than 0 and click on submit button, loop checks each input value and if value!=0 , script collects new value and its input name and then post it into database.

For example, if input field named "One" gets new value "2" and input field named "Five" gets new value "1", script posts in database One 2; Five 1; One 2; Five 1; and skips all other fields with value 0.

Or is it maybe easier to create form with table instead of input fields to do this?

Sorry for my bad English and thank you in advance.

var inputs = document.getElementById('form').children;
var data = {};
for(var i in inputs ){
    if(inputs[i].value != 0)data[inputs[i].name] = inputs[i].value;
}

// do Post-Request with XHR here using data which holds all values

Since your tag has jquery, here is a jquery way to intercept submit and only post changed values. You would replace the part that outputs text to post. See this updated fiddle .

Html:

<form method="post" action="" id="form"> 
    <input type='text' class='textInput' name="One"  id="one" value='0'>
    <input type='text' class='textInput' name="Two"  id="two" value='0'>
    <input type='text' class='textInput' name="Three"  id="three" value='0'>
    <input type='text' class='textInput' name="Four"  id="four" value='0'>
    <input type='text' class='textInput' name="Five"  id="five" value='0'>
    <input type='text' class='textInput' name="Six"  id="six" value='0'>
    <input type='text' class='textInput' name="Seven"  id="seven" value='0'>
    <input type='text' class='textInput' name="Eight"  id="eight" value='0'>
    <input type="submit" id='submit' value="Submit">
</form>
<p id='output'></p>    

Javascript:

$('form').submit(function(){    
    $('.textInput').each(function(){ 
        if($(this).val() != '0')
        {
            $('#output').text($('#output').text()+ ' ' + $(this).attr('name') + ':' + $(this).attr('value') );
        }
    });
    return false;
});

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