I have the following form:
<input type="text" name="name1" id="names1" class="names" value="" placeholder="1) Name Here . . .">
<input type="text" name="name2" id="names2" class="names" value="" placeholder="2) Name Here . . .">
<input type="text" name="name3" id="names3" class="names" value="" placeholder="3) Name Here . . .">
<input type="text" name="name4" id="names4" class="names" value="" placeholder="4) Name Here . . .">
I am trying to create an array when the user clicks the submit button that stores each name:
var values = $('.names').map(function() { return this.value; }).get();
It works, but it also collects the empty fields which I do not need. I figure I require a conditional For statement for this, but I can't manage the syntax for it.
Thanks
Try this:
var values = $('.names').map(function() { if(this.value.trim() != '') return this.value; }).get();
Or:
var result = [];
var elements = getElementsByClassName('names');
for(var i = 0; i < elements.length; i++){
if(elements[i].value.trim() != '')
result.push(elements[i].value);
}
just select all .names with non empty value
var values = $('.names[value!=""]').map(function() { return this.value; }).get();
in real world you will need to store names also:
var values = $('.names[value!=""]').map(function() {
return {name: this.name,value: this.value};
}).get();
http://jsfiddle.net/oceog/7ZcbY/
Related
I have 2 input boxes for first name and last name of passengers travelling.
There could be maximum 9 number of passengers.
It is not allowed to have two passengers with same name(first and last combined)
How can I check if none of the passenger have same names(first and last name combined)
<input type="text" name="adultFirstName1" id="adultFirstName1" class="form-control input-sm" placeholder="" style="width:100%; padding:5px;">
Thanks.
Edit:
I am not using a database to store the passenger names and the passengers are all entered on the same page.
You can add a verification javascript function , but first u need to have specific names for all input boxes .
U can try something like this :
<input type="text" name="adultFirstName1" id="adultFirstName1" class="form-control input-sm" placeholder="" style="width:100%; padding:5px;" OnClick="Verify();">
.
.
.
<input type="text" name="adultFirstName10" id="adultFirstName10" class="form-control input-sm" placeholder="" style="width:100%; padding:5px;" OnClick="Verify(id);">
then you'll need to verify at every change of value of a boxe .
var name=[];
var sameName=false;
for(var i=1;i<=<%=detailsModel.getNumberOfAdult()%>;i++)
{
var fullName = document.getElementById("adultFirstName"+i).value+" "+document.getElementById("adultLastName"+i).value
name.push(fullName);
}
for(var i=1;i<=<%=detailsModel.getNumberOfChild()%>;i++)
{
var fullName = document.getElementById("childFirstName"+i).value+" "+document.getElementById("childLastName"+i).value
name.push(fullName);
}
for(var i=1;i<=<%=detailsModel.getNumberOfInfant()%>;i++)
{
var fullName = document.getElementById("infantFirstName"+i).value+" "+document.getElementById("infantLastName"+i).value
name.push(fullName);
}
for(var i=0;i<name.length;i++)
{
for(var j=i+1;j<name.length;j++)
{
if(name[i]==name[j])
{
var sameName=true
valid= false;
}
}
}
if(sameName==true)
{
$('#sameNameError').html('2 Passengers Cannot Have Same Name');
}
else
{
$('#sameNameError').html('');
}
Are there 2 input boxes for each passenger? If so, try something like this:
$(document).ready(function(){
$("button").click(function(){
if($("#adultFirstName1").val() == $("#adultFirstName2").val()
&& $("#adultLastName1").val() == $("#adultLastName2").val()) {
//Names are the same
}
});
});
Or are you needing to check against the names of other passengers already in a database somewhere?
let us say that there is 5 input field for page (A)
<form class="classesName" action="action.php" method="POST">
<input type="text" name="class1" placeholder="Class Name1?" required="">
<input type="text" name="class2" placeholder="Class Name2?" required="">
<input type="text" name="class3" placeholder="Class Name3?" required="">
<input type="text" name="class4" placeholder="Class Name4?" required="">
<input type="text" name="class5" placeholder="Class Name5?" required="">
</form>
I want the user to fill all the fields BUT it must be unique class name for each field
so he can't fill
class a
class b
class a < this one is duplicated so it should display an error message
class c
class d
I think I can make if statement in the action.php page to check is there a duplication in the submitted field or not
but I don't want all the other values to be lost when I reload this page again to display the error for him
is there like a property in html5 or anything like that ?
thanks
No, this cannot be done with HTML5 alone. You'll have to write some JavaScript to make this happen. The JavaScript code should check all the values and if any two are identical prevent the form from submitting successfully.
In this case you could use javascript to validate the fields every time the user fills out a textbox. Here is an example:
$('input[type=text]').on('change',function(){
var arr = [];
$siblings = $(this).siblings();
$.each($siblings, function (i, key) {
arr.push($(key).val());
});
if ($.inArray($(this).val(), arr) !== -1)
{
alert("duplicate has been found");
}
});
JSFiddle: http://jsfiddle.net/x66j3qw3/
var frm = document.querySelector('form.classesName');
var inputs = frm.querySelectorAll('input[type=text]');
frm.addEventListener('submit', function(e) {
e.preventDefault();
var classArr = [];
for(var i = 0; i < inputs.length; i++) {
if(classArr.indexOf(inputs[i].value) != -1) {
inputs[i].style.backgroundColor = "red";
return false;
}
else
classArr.push(inputs[i].value);
}
frm.submit();
});
jsfiddle DEMO
When I select one product, its ID will be passed to the javascript code below
$(document).ready(function(){
$("#nameinput_1").click(function(){
var id = $('#nameinput_1').val();
$.post("vfiles/data/ajaxload_buy.php",
{
id:id,
},
function(html){
$("#input_1").val(html);
});
});
});
which will then produce the price at input_1
<input type="text" name="nameinput_1" id="nameinput_1"> <input type="text" name="input_1" id="input_1">
<input type="text" name="nameinput_2" id="nameinput_2"> <input type="text" name="input_2" id="input_2">
How can I code nameinput_1 so that it automatically changes when I choose a new product without me rewriting it as nameinput_2 ( ex: i --> i++ ). I don't have good ground in javascript so if possible, please help me calculate the sum of input_1 and input_2. Then assign the sum to a new input value.
file ajaxload_buy.php
$ID= $_POST['id'];
$sql = "SELECT * FROM produce WHERE ID = '".mysql_real_escape_string($ID)."'";
$result = mysql_query($sql)
or die(mysql_error());
$row = mysql_fetch_array($result);
echo $row['price'];
I fix this:
I write this so that you have the right not
$(document).ready(function(){
$(".nameinput").click(function() {
var input = this.name.replace('name', '');
$.post("vfiles/data/ajaxload_buy.php", {id: this.value}, function(html) {
$("#" + input).val(html);
$(this).next().val(html);
var sum = 0;
$(".price").each(function() {
sum += parseFloat($(this).html());
});
**$("#export").val(sum);**
});
});
});
How can I export these data in a new input
var sum = 0;
$(".price").each(function() {
sum += parseFloat($(this).html());
});
**$("#export").val(sum);**
I do not understand the value (sum) export = NaN
problem is solved
var sum = 0;
$(".price").each(function() {
sum += Number(this.value);
});
Here is some suggestions:
First, use class instead of id so you don't need to duplicate your code. Do something like $(".getprice") instead of $("#nameinput_1") and use next() to select the input element you need:
<input type="text" class="getprice" name="nameinput_1" id="nameinput_1"> <input type="text" name="input_1" id="input_1">
<input type="text" class="getprice" name="nameinput_2" id="nameinput_2"> <input type="text" name="input_2" id="input_2">
And
$(document).ready(function(){
$(this).click(function(){
var id = $(this).val();
$.post("vfiles/data/ajaxload_buy.php",
{
id:id,
},
function(html){
$(this).next().val(html);
});
});
});
Second, if you are sure you have only two things to add up then it's easy to implement based on what you have done. But I still suggest you use a class. Let's say 'price' then the html would be:
<input type="text" class="getprice" name="nameinput_1" id="nameinput_1"> <input type="text" name="input_1" class="price" id="input_1">
<input type="text" class="getprice" name="nameinput_2" id="nameinput_2"> <input type="text" name="input_2" class="price" id="input_2">
Then you can use each to do something like this when you need to sum prices up:
var sum = 0;
$(".price").each(function() {
sum += parseFloat($(this).html());
});
Well if you know the id of the new input then it's as simple as $("#id_of_the_input").val(sum);
I'm trying to get this thing work for a while but I guess I need to tweak the code from somewhere. I thought, someone here could better guide me instead of banging my head to my coding screen :)
here's the actual process:
<input type="hidden" name='oneSelectionChk_1'>
<input type="checkbox" name='awp_group_1' id='id1'>
<input type="checkbox" name='awp_group_1' id='id2'>
<input type="checkbox" name='awp_group_1' id='id3'>
<input type="checkbox" name='awp_group_1' id='id4'>
<input type="hidden" name='oneSelectionChk_2'>
<input type="checkbox" name='awp_group_2' id='id5'>
<input type="checkbox" name='awp_group_2' id='id6'>
<input type="checkbox" name='awp_group_2' id='id7'>
<input type="checkbox" name='awp_group_2' id='id8'>
<input type="hidden" name='oneSelectionChk_3'>
<input type="checkbox" name='awp_group_3' id='id9'>
<input type="checkbox" name='awp_group_3' id='id10'>
<input type="checkbox" name='awp_group_3' id='id11'>
<input type="checkbox" name='awp_group_3' id='id12'>
what I'm using for jQuery is:
var chkFields = $("input[name='oneSelectionChk']");
$.each(chkFields, function(i, field){
var groupID = field.id.split('_'); // Getting the ID of the group
var chkGroupBoxes = $('input[name="awp_group_"'+groupID[1]);
if(field.value==1)
{
//$.each(chkGroupBoxes, function(j, thisChkBox){
//alert(thisChkBox.value + " #"+j);
alert( $('input[name="awp_group_"'+groupID[1]).filter(':checked').length);
if($('input[name="awp_group_"'+groupID[1]+':checked').length > 0 )
{
//$.scrollTo( '#awp_container', 1200 );
alert($('input[name="awp_group_"'+groupID[1]+':checked').length+" Selected ");
//alert( "Class AlertMsgText Should be removed Now");
$("#selectInstruction_"+groupID[1]).removeClass("AlertMsgText");
//return
}
else
{
alert($('input[name="awp_group_"'+groupID[1]+':checked').length+" Still not selected ");
//alert("Please select atleat 1 from Option #"+groupID[1]);
$("#selectInstruction_"+groupID[1]).addClass("AlertMsgText");
$.scrollTo( '#awp_container', 1200 );
//return;
}
//});
}
});
This code always giving me 0 length of checkboxes, I'm not sure if I need to loop through again for each checkbox or this might work?
Any quick help should be appreciated!
Try
var chkFields = $('input[name^="oneSelectionChk"]');
$.each(chkFields, function (i, field) {
var groupID = field.name.replace('oneSelectionChk_', '')
var chkGroupBoxes = $('input[name="awp_group_' + groupID + '"]');
if (chkGroupBoxes.filter(':checked').length == 0) {
alert('please select at least one checkbox under: ' + field.name)
}
});
Demo: Fiddle
There is no element with name attribute of oneSelectionChk in your markup, the hidden inputs have name attributes that start with oneSelectionChk, you have to use attribute starts with selector.
In case that elements are siblings you can select the target elements using .nextUntil() method:
var $hidden = $('input[type=hidden]').filter('[name^=oneSelectionChk]');
$hidden.each(function(){
var $chekboxes = $(this).nextUntil('input[type=hidden]'),
$checked = $checkboxes.filter(':checked'),
$unchecked = $chekboxes.not($checked);
});
Using name attributes:
var $hidden = $('input[type=hidden]').filter('[name^=oneSelectionChk]'),
$checkboxes = $('input[type=checkbox]');
$hidden.each(function() {
var n = this.name.split('_')[1];
var $grp = $checkboxes.filter('[name="awp_group_'+ n +'"]');
// ..
});
If I have 50 pairs of input textboxes, i.e.
<input type="text" id="name_0" /><input type="text" id="name_1" />
<input type="text" id="dept_0" /><input type="text" id="dept_1" />
...
<input type="text" id="age_0" /><input type="text" id="age_1" />
<input type="text" id="weight_0" /><input type="text" id="weight_1" />
i.e 50 variables of these.
When the page loads, I populate each pair with identical data.
What is the best way to check if the _0 is different from the _1?
then returning a message showing which pair has changed.
The comparison should take place once the values have been changed and a button is clicked.
$("input[type=text]").each(function () {
var $this = $(this);
if ( /_0$/.test(this.id) ) {
if ( $this.val() != $this.next("input").val() ) {
$this.css("color", "red"); // or whatever
}
}
});
Tomalak's answer should work, but just in case your inputs are scattered or not necessarily beside each other, something like this should suffice.
$('input:text[id$="_0"]').each(function() {
var new_id = this.id.replace('_0','_1');
if ($(this).val() !== $('input#'+new_id).val()) {
// not the same
}
});
var changed = [];
$("[id$=_0]").each(function() {
var name = this.id.replace("_0", "");
if (this.value != $("#" + name + "_1").val()) {
changed.push(name);
}
});
console.log(changed);