简体   繁体   中英

Javascript/JQuery multiple input, get input position

I have a form with multiple input with same name. User will be able to add/remove the input line dynamically. eg.

<div><select name="Car[]"></select> <input name="Qty[]"></div>
<button> Add another line</button>

With user interaction, there's a possibility it will become:

<div><select name="Car[]"></select> <input name="Qty[]"></div>
<div><select name="Car[]"></select> <input name="Qty[]"></div>
<div><select name="Car[]"></select> <input name="Qty[]"></div>
.......
<button> Add another line</button>

The add button just make a clone of the parent () and append it below.

I want to enforce eg Honda Civic, the only allowed qty is less than 9. Toyota Prius qty is less than 17...

The enforcement will be using on jquery.change() function. $(input[name="Qty"]).change)

$( input[name="Qty"] ).change(function() {
   if(***value car*** == "Honda Civic" && $(this).val() > 9) $(this).val(0);
   else if(***value car*** == "Toyota Prius" && $(this).val() > 17) $(this).val(0);
   else if(***value car*** == "Maserati Ghibli" && $(this).val() > 3) $(this).val(0); 
});

How can I get the input quantity position, and get the value of input car?

Can't you create an object which stores car names to limits? For example:

var carLimits = {
    'Honda Civic': '8',
    'Toyota Prius': '16'
};

You could then just count how many 'things' the user has added.

hondaCivicCount++

And then create an if statement to check if the hondaCivicCount is less than than, or equal to the carLimit before adding a 'thing'.

You'd be best of doing some sort of server-side verification though, if whatever you're doing needs to be secure.

Try Jquery .size() it will tell how much select or input u have https://api.jquery.com/size/ .

and get value by using .each() https://api.jquery.com/each/

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