Good evening. I had a task to select all inputs with one name attribute and write their values to an array, and then delete all empty values. Since the same forms are added on the same page and adding the id of the form does not make sense, since the same id of the forms on one page is an error. I use Jquery and this option: var phone = $('input[name=\'phone\']').attr('value'); adds an empty value to the variable.
|
3 answers
Try it like this. I would just like to caution against using identical input name , in order to avoid any errors.
var phones = $('input[name*="phone"]'); var arr = []; phones.each(function() { if (this.value != "") { arr.push(this.value); } }); console.log(arr); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input name="phone1" value="53453466456456" /> <input name="phone2" value="854634545" /> <input name="phone3" value="" /> <input name="phone4" value="4236456" /> - thanks !!! .... this option came up, I would have thought how to do it myself - Ivan Triumphov
- "I would just like to warn against using the same name for input" - I understand that, but the fact is that I am doing custom integration and, unfortunately, the developers haven’t taken this into account - Ivan Triumphov
|
$(function() { var phones = []; $('input[name="phone"]').each(function() { if ($(this).val() !== '') { phones.push($(this).val()); } }); console.log(phones); $('.res').text(phones); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type="text" name="phone" value="100-500"> <input type="text" name="phone" value="(095) 000-99-33"> <input type="text" name="phone" value=""> <input type="text" name="phone" value="(044) 155-66-77"> <input type="text" name="phone" value="30-66-99"> <br>Результат: <div class="res"></div> - @IvanTriumphov Added processing of empty inputs. - Jean-Claude
- well yes ... your options are very similar - Ivan Triumphov
|
You can do several ways, here are two of them:
$('input[name="name"]').filter(function() { return this.value == ""; }); $('input[name="name"]').filter(function() { return $(this).val() == ""; }); Return the array of inputs with the name name and empty value.
|