How to loop through the form which has random elements - javascript

I am trying to loop through the form which has label inside random elements and check if the label matches with the given label name and if matches, I am adding a class to that element. But I am not able get it working, how can I do this?
Here's what I have tried.
Form which has labels inside random elements like div
<form id="grtform">
<div id="section-1">
<lable>Currency type</lable>
<input type="text" name="currencyType">
</div>
<div id="section-2">
<lable>Currency rate</lable>
<input type="text" name="currencyRate">
</div>
<lable>Currency of country</lable>
<input type="text" name="currencyCountry">
<div id="section-3">
<div class="formData">
<lable>Currency due</lable>
<input type="text" name="currencyDue">
</div>
</div>
</form>
Jquery code:
$("#grtform").each(function(){
var matchLable = "Currency due"
var lable = $(this).find('label').text();
if(matchLable == lable){
$(this).addClass('matchFound');
}
});

You need loop through lables, not against form
$("#grtform lable").each(function(){ // selecting all labels of form
var matchLable = "Currency type"
var lable = $(this).text(); // changed here too
if(matchLable == lable){
$(this).addClass('matchFound');
}
});
In above code, this refers to currently iterating label.
After trimming a bit
$("#grtform lable").each(function(){ // selecting all labels of form
if($(this).text() == "Currency type"){
$(this).addClass('matchFound');
}
});

You can also use following way :-
var allLables = document.querySelectorAll("#grtform lable");
for(var i = 0; i < allLables.length; i++){
var matchLable = "Currency type";
var lable = allLables[i].innerText; // changed here too
if(matchLable == lable){
allLables[i].classList.add("matchFound");
}
}
<form id="grtform">
<div id="section-1">
<lable>Currency type</lable>
<input type="text" name="currencyType">
</div>
<div id="section-2">
<lable>Currency rate</lable>
<input type="text" name="currencyRate">
</div>
<lable>Currency of country</lable>
<input type="text" name="currencyCountry">
<div id="section-3">
<div class="formData">
<lable>Currency due</lable>
<input type="text" name="currencyDue">
</div>
</div>
</form>

Related

Calc two fields and set results in third

I have a problem with the script.
I am trying to count two input fields, and insert the result into the third field.
But it doesn't work, and unfortunately I can't figure out what's wrong.
function sum() {
var txtFirstNumberValue = document.querySelectorAll('#firstID > div > div > div > input').value;
var txtSecondNumberValue = document.querySelectorAll('#second > div > div > div > input').value;
if (txtFirstNumberValue == "")
txtFirstNumberValue = 0;
if (txtSecondNumberValue == "")
txtSecondNumberValue = 0;
var result = parseInt(txtFirstNumberValue) / parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.querySelectorAll('#third > div > div > div > input').value = result;
}
}
<div id="firstID"><div>
<label>first</label>
<div>
<div>
<input name="drts[field_first][0]" type="number" value="" maxlength="255">
</div>
</div>
</div></div>
<div id="second"><div>
<label>second</label>
<div>
<div>
<input name="drts[field_second][0]" type="number" maxlength="255">
</div>
</div>
</div></div>
<div id="third"><div>
<label>third</label>
<div>
<div>
<input name="drts[field_third][0]" type="number" value="" maxlength="255">
<div></div>
</div>
</div>
</div></div>
There are a few problems here.
Are you actually calling sum? I've added a call in the example code so you can run it.
Your query selectors are not right. There isn't actually anything in the divs with the IDs you query. I've moved the input boxes into the correct places. When debugging, you should check that you are actually finding elements in your querySelectorAll call before proceeding.
querySelectorAll doesn't have a value property. You would need to iterate over each element before getting the items. Given you specifically want one item, it would be better to use something more specific like getElementById. I've kept the original querySelectorAll but changed the IDs on the divs to classes so we can have more than one result for this example. Then, I iterate over them pulling out the value to add to result. I've moved the parseInt to the running calculation otherwise it would perform a string concatenation.
Even better than the above would be to access the input directly. There's probably no point accessing a div and drilling down to the input. I've included this example to output the result.
I've removed redundant html. It's not related to the answer but try to keep your markup clean.
function sum() {
var inputElements = document.querySelectorAll('.user-input > div > div > input');
var result = 0;
inputElements.forEach(element => {
result += element.value ? parseInt(element.value) : 0
})
document.getElementById('third').value = result
}
document.getElementById('run-button').addEventListener('click', sum)
<div class="user-input">
<label>first</label>
<div>
<div>
<input name="drts[field_first][0]" type="number" maxlength="255">
</div>
</div>
<div>
<div class="user-input">
<label>second</label>
<div>
<div>
<input name="drts[field_second][0]" type="number" maxlength="255">
</div>
</div>
<div>
<label>third</label>
<div>
<div>
<input id="third" name="drts[field_third][0]" type="number" value="" maxlength="255">
<div></div>
</div>
</div>
<div>
<button type="button" id="run-button">Run</button>
Try like this
function sum() {
let txtFirstNumberValue = document.querySelector('#firstID input').value;
let txtSecondNumberValue = document.querySelector('#second input').value;
let result = parseInt(txtFirstNumberValue) / parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.querySelector('#third input').value = result;
} else {
document.querySelector('#third input').value = '';
}
}
<div id="firstID"><div>
<label>first</label>
<div>
<div>
<input name="drts[field_first][0]" type="number" value="" maxlength="255">
</div>
</div>
</div></div>
<div id="second"><div>
<label>second</label>
<div>
<div>
<input name="drts[field_second][0]" type="number" maxlength="255">
</div>
</div>
</div></div>
<div id="third"><div>
<label>third</label>
<div>
<div>
<input name="drts[field_third][0]" type="number" value="" maxlength="255" disabled>
<div></div>
</div>
</div>
<div>
<button id="button" onclick="sum()">Calculate</button>
</div>
</div>
</div>
const input1 = document.querySelector('#input1');
const input2 = document.querySelector('#input2');
const input3 = document.querySelector('#input3');
const storeInputs = [input1, input2];
for(let i = 0; i < storeInputs.length; i++) {
storeInputs[i].addEventListener('input', function() {
// multiply input1 and input2 with 1 for converting there values from string to number
input3.value = input1.value * 1 + input2.value * 1;
});
};
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<label for="input1">First Input</label>
<input id="input1" type="number" value="0"></input>
<label for="input2">Second Input</label>
<input id="input2" type="number" value="0"></input>
<label for="input3">Third Input</label>
<input id="input3" type="number" value="0"></input>
</body>
</html>

When i add new input field for phone to my form , i need it to show Phone 2 ..Phone 3 etc

I have a form , in which there is a Phone 1 input filed. When i click "Add Phone " button i need it to display new input field that says Phone 2 ...Phone 3 , etc. I got it to work with showing Phone 2 only , every time when the button is clicked , but my approach is not the correct one , as i believe i need to have an IF statement , so that it can change the number phone - 2,3,4,5.
function newPhone () {
var phone = document.querySelector('.phone');
var label = document.createElement('label') ;
var input = document.createElement('input')
var span = document.createElement('span')
span.textContent= 'Phone 2';
input.setAttribute('type','text')
input.setAttribute('name', 'phones')
label.appendChild(span);
phone.appendChild(label);
phone.appendChild(input)
}
<form id="form">
<div class="field">
<label>First name</label><input type="text">
</div>
<div class="field">
<label>Last name</label><input type="text">
</div>
<div class="field">
<strong>Phones</strong>
<div id="list-phones">
<div class="phone">
<label>Phone <span>1</span></label><input name="phones[]"
type="text">
</div>
</div>
</div>
<button id="add_phone" type="button" onclick="newPhone()">Add
phone</button>
</form>
Just make a variable to keep track of number. i.e. i here.
var i = 1;
function newPhone () {
i++;
var phone = document.querySelector('.phone');
var label = document.createElement('label') ;
var input = document.createElement('input')
var span = document.createElement('span')
span.textContent= 'Phone '+i;
input.setAttribute('type','text')
input.setAttribute('name', 'phones-'+i)
label.appendChild(span);
phone.appendChild(label);
phone.appendChild(input)
}
<form id="form">
<div class="field">
<label>First name</label><input type="text">
</div>
<div class="field">
<label>Last name</label><input type="text">
</div>
<div class="field">
<strong>Phones</strong>
<div id="list-phones">
<div class="phone">
<label>Phone <span>1</span></label><input name="phones-1"
type="text">
</div>
</div>
</div>
<button id="add_phone" type="button" onclick="newPhone()">Add
phone</button>
</form>

How to check if input name is inside an array in Jquery?

I want to know how I can check if input name is equal to name inside an array.
I have multiple inputs like below code:
<div class="inputMain">
<input name="first_name" value="">
</div>
<div class="inputMain">
<input name="last_name" value="">
</div>
<div class="inputMain">
<input name="email" value="">
</div>
And I have an array Like this:
var array = ['last_name', 'email'];
I want to add class to div, that wrap the input his name inside the array.
I don't want to use 2 loops.
You can use the following code:
var inputs = $("input");
var array = ['last_name', 'email'];
inputs.each(function(){
if(array.indexOf($(this).attr("name")) >= 0){
alert($(this).attr("name")+" exists");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="inputMain">
<input name="first_name" value="">
</div>
<div class="inputMain">
<input name="last_name" value="">
</div>
<div class="inputMain">
<input name="email" value="">
</div>
The HTML to the code is same as used by you in your question, I have added a bit of JQuery, that is simple to understand.
I hope it was helpful.
check output in browser console:
$(document).ready(function() {
var array = ['last_name', 'email', 'dsfdsfds'];
array.forEach(function(element) {
var x = document.getElementsByName(element);
console.log(x);
});
});
//check output in browser console
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<div class="inputMain">
<input name="first_name" value="">
</div>
<div class="inputMain">
<input name="last_name" value="">
</div>
<div class="inputMain">
<input name="email" value="">
</div>
there is your solution :)
$(document).ready(function() {
var array = ['last_name', 'email'];
var inputs = $("div[class='inputMain']").find("input");
array.forEach(function(name) {
inputs.each(function (x){
if (inputs[x].name === name) {
inputs[x].parentNode.classList.add("myClass")
}
});
});
console.log(inputs.prevObject);
});
https://jsfiddle.net/12es37ko/62/
you can check result into browser console :)

php foreach loop and addmore button in a form

hello i am using a form to add experience to users where i have a add more button which adds more (clones) the content and users get one more field to add experience
i am using this code to achieve this
<div id="append_palllsjjs"><div class="full_exp_9092k" id='duplicater'>
<div class="full_one_row_009so">
<div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
Company Name <span>*</span>
</div>
<div class="maind_TAxefst67s77s">
<input type="text" name="comp[]" required placeholder="company Name" class='cname_990s_EXp'/>
</div>
</div><div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
Department Name <span>*</span>
</div>
<div class="maind_TAxefst67s77s">
<input type="text" name="dept[]" required placeholder="Department Name" class='cname_990s_EXp'/>
</div>
</div>
</div><div class="full_one_row_009so">
<div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
From Date <span>*</span>
</div>
<div class="maind_TAxefst67s77s">
<input type="date" data-initial-day="1" data-initial-year="2011" data-initial-month="9" class='TEx_About_allihh' name="exsdate[]" required/>
</div>
</div><div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
To Date <span>*</span>
</div>
<div class="maind_TAxefst67s77s">
<input type="date" data-initial-day="1" data-initial-year="2012" data-initial-month="10" class='TEx_About_allihh' name="exedate[]" required/>
</div>
</div>
</div><div class="full_one_row_009so">
<div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
Profile <span>*</span>
</div>
<div class="maind_TAxefst67s77s">
<input type="text" name="profile[]" required placeholder="Profile" class='cname_990s_EXp'/>
</div>
</div><div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
</div>
<input type="button" name="addmore" value="Add More" class='button small white' onclick='duplicate();'/>
</div>
</div>
</div></div>
js
var i = 0;
var original = document.getElementById('duplicater');
function duplicate() {
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplicetor" + ++i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
}
here i want the new fields when added should be empty (right now it is showing the same content with pre filled values in textbox )
second issue is i want to insert the data in table for each value of the array i know this can be donr by foreach loop
PHP
$comps=$_POST['comp'];
$profile=$_POST['profile'];
$exedate=$_POST['exedate'];
$exsdate=$_POST['exsdate'];
$dept=$_POST['dept'];
if(empty($comps) || empty($profile) || empty($exedate) || empty($exsdate) || empty($dept) ){
echo 'Please Fill all the fields marked with *';die;
}
foreach($comps as $value){
// insert into tablename (field1,field2,field3,...) values ('comp1','dep1','profile1'....)
// insert as many feilds as the no of elements in the array
}
please suggest me with this php code how to use the foreach loop so that i can insert as many rows as the no of elements in the array with corrosponging values in another array
pleaes note that this question has two questions written please feel free to help for any of the question.
one is wth php and anothr with ajax
Use following code to clear Cloned form :
NOTE : Must add jquery file in document
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
var i = 0;
var original = document.getElementById('duplicater');
function duplicate(){
var clone = original.cloneNode(true); // "deep" clone
i = ++i;
clone.id = "duplicetor"+ i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
clearCloneForm(clone.id);
}
function clearCloneForm(id){
var divId = '#'+id;
$(divId).find("input[type^='text'], input[type^='date']").each(function() {
$(this).val('');
});
}
</script>
Here is code with your new requirement :
To Add remove button if user want to remove form block section user
can easily :
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
var i = 0;
var original = document.getElementById('duplicater');
function duplicate(){
var clone = original.cloneNode(true); // "deep" clone
i = ++i;
clone.id = "duplicetor"+ i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
addButton(clone.id,i);
clearCloneForm(clone.id);
}
function clearCloneForm(id){
var divId = '#'+id;
$(divId).find("input[type^='text'], input[type^='date']").each(function() {
$(this).val('');
});
}
function addButton(id,ii){
var divId = '#'+id;
$(divId).append('<input type="button" value="Remove" class="button small white" id="'+ii+'" onclick="rBlock('+ii+')" />');
}
function rBlock(ii){
$('#'+ii).on('click', function(e){
var parentDiv = $(this).parent();
if(parentDiv.attr('id') !== ii){
parentDiv.remove();
}
});
$('#'+ii).trigger( "click" );
}
</script>

Getting all child input elements within a div

I am trying to get all the values of the input fields. The issue is all of the <input type=radio/> are dynamic and can increase or decrease at any time.
So I am starting with the main DI and going from there. The problem I have now is I am not getting the input radio buttons values.
So here are the steps I am intending to accomplish:
If any radio button is selected, pass its value to the checkbox value,
If the radio button is selected and the checkbox is not selected, do not pass to the checkbox value
I am looking for a solution in JavaScript only - do not use jQuery
Here is my jsFiddle code
HTML
<div style="display: block;" id="mymainDiv" class="fullFloat">
<input type="hidden" value="1" id="startIdxShMdeCarWisevId" name="startIdxShMdeCarWise">
<div class="subTitle">UPS<a class="fRight" onclick="localG('10',false,0,false,'UPS','1','$');" href="javascript:void(0);">Show Prices</a></div>
<div style="display:none;" id="Wheel_UPS"><div class="loadingcheckout"></div></div>
<div id="Price_UPS">
</div>
<div class="wrapLeft wrapClear">
<div class="wrapleft">
<label class="">
<input type="radio" value="11098" id="deliveryMethodId_1" name="deliveryMethodId" class="section" data-mask="" data-rev="" data-rel="false" data-carrier="">
<span>
UPS Ground (Order by 9:30 PM EST)
</span>
<div class="wrapRight">
<div id="UPS_11098">
</div>
</div>
</label>
</div>
<input type="text" value="1" id="UPS">
</div>
<input type="hidden" value="2" id="startIdxShMdeCarWisevId" name="startIdxShMdeCarWise">
<div class="subTitle">Standard<a class="fRight" onclick="localG('20',false,0,false,'Standard','2','$');" href="javascript:void(0);">Show Prices</a></div>
<div style="display:none;" id="Wheel_Standard"><div class="loadingcheckout"></div></div>
<div id="Price_Standard">
</div>
<div class="wrapLeft wrapClear">
<div class="wrapleft">
<label class="">
<input type="radio" value="11117" id="deliveryMethodId_2" name="deliveryMethodId" class="section" data-mask="" data-rev="" data-rel="false" data-carrier="">
<span>
Standard Delivery - 2-3 Day Delivery at Ground Rate (Order by 9:30 PM EST)
</span>
<div class="wrapRight">
<div id="Standard_11117">
</div>
</div>
</label>
</div>
<input type="text" value="1" id="Standard">
</div>
<input type="hidden" value="3" id="startIdxShMdeCarWisevId" name="startIdxShMdeCarWise">
<div class="subTitle">FedEx<a class="fRight" onclick="localG('190',false,0,false,'FedEx','3','$');" href="javascript:void(0);">Show Prices</a></div>
<div style="display:none;" id="Wheel_FedEx"><div class="loadingcheckout"></div></div>
<div id="Price_FedEx">
</div>
<div class="wrapLeft wrapClear">
<div class="wrapleft">
<label class="">
<input type="radio" value="11088" id="deliveryMethodId_3" name="deliveryMethodId" class="section" data-mask="" data-rev="" data-rel="false" data-carrier="">
<span>
FedEx Ground (Order by 8:00 PM EST)
</span>
<div class="wrapRight">
<div id="FedEx_11088">
</div>
</div>
</label>
</div>
<input type="text" value="1" id="FedEx">
</div>
</div>
<input type="checkbox" name="shipmode" id="shipmode" value="" onclick="getpref('mymainDiv');">Get Value
JS Code
This executes when the checkbox is clicked:
function getpref(val) {
var wr = document.getElementById(val);
childElements = wr.childNodes;
//alert(childElements);
for(var i = childElements.length-1; i>=0; i--){
var elem = childElements[i];
console.log(elem.id);
if(elem.id && elem.id.indexOf(val+'_')==0){
elem.style.display = 'block';
}
}
//alert(val);
}
You can directly access input nodes in your DIV with getElementsByTagName
function getpref(val) {
var divNode = document.getElementById(val);
var inputNodes = divNode.getElementsByTagName('INPUT');
for(var i = 0; i < inputNodes.length; ++i){
var inputNode = inputNodes[i];
if(inputNode.type == 'radio') {
//Do whatever you want
if(inputNode.checked) {
//Do whatever you want
}
}
}
}
Example: http://jsfiddle.net/88vp0jLw/1/
You can use getElementsByName to get you all of the radio buttons by name='deliveryMethodId' and then go from there:
function getpref(val) {
var radioButtons = document.getElementById(val).getElementsByName("deliveryMethodId");
for(var i = radioButtons.length-1; i>=0; i--)
{
var radioButton = radioButtons[i];
if(radioButton.checked)
console.log(radioButton.id + " is selected ");
}
}

Categories