Hiding a div if a value is under 1 - javascript

I want the application to behave this way so that when I click on "Show Order" if any of the values are 0 or blank, I don't want div id item * x be shown:
var divs = document.getElementsByTagName('div');
var toggle = function() {
for (var i = 0, l = divs.length; i < l; i++) {
if (divs[i].getAttribute('class') == 'problem')
if (divs[i].style.display == 'none') divs[i].style.display = '';
else divs[i].style.display = 'none';
var x = document.getElementById("mySelect").value;
var y = document.getElementById("item1").value;
if (x < 1) {
y.style.display === "none"
} else {
document.getElementById("demo").innerHTML = x;
}
var x = document.getElementById("mySelect1").value;
document.getElementById("demo1").innerHTML = x;
var x = document.getElementById("mySelect2").value;
document.getElementById("demo2").innerHTML = x;
}
}
document.getElementById('Toggle').onclick = toggle;
<div class="problem">
<div class="row">
<div class="col-3">
<form>
<input type="number" id="mySelect" name="mySelect" autocomplete="off" style="width: 3em;"> Sausage
<br>
</form>
</div>
<div class="col-3">
<form>
<input type="number" id="mySelect1" name="mySelect1" autocomplete="off" style="width: 3em;"> Pancake
<br>
</form>
</div>
<div class="col-2">
<form>
<input type="number" id="mySelect2" name="mySelect2" autocomplete="off" style="width: 3em;"> Milk
</form>
</div>
<div class="col-4">
</div>
</div>
<div class="row">
<div class="col-12">
<p>
<button type="button" class="button" id="Toggle" onclick="myFunction()">Show Order</button>
</p>
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<div style="display:none;" class="problem">Please show this to the cashier.</div>
<div style="display:none;" class="problem">
<h2>Hello, they ordered:</h2>
</div>
<div id="item1" style="display:none;" class="problem">
<h2><span style="font-size: xx-large; color: green;" id="demo"></span>x Sausage(s)</h2>
</div>
<div id="item2" style="display:none;" class="problem">
<h2><span style="font-size: xx-large; color: green;" id="demo1"></span>x Pancake(s)</h2>
</div>
<div id="item3" style="display:none;" class="problem">
<h2><span style="font-size: xx-large; color: green;" id="demo2"></span>x Cup of Milk(s)</h2>
</div>
<div style="display:none;" class="problem">
<h2>Thank you</h2>
</div>
<div style="display:none;" class="problem">Please refresh your browser to restart your order</div>
</div>
</div>
I have added my full code from JSFiddle here.

Check this simpler approach
Give a display class to div to be div to be toggled
Check for any input values to be >= 1
Demo
var toggle = function() {
var x1 = Number(document.getElementById("mySelect").value);
var x2 = Number(document.getElementById("mySelect1").value);
var x3 = Number(document.getElementById("mySelect2").value);
document.querySelectorAll(".display .problem").forEach(function(el) {
el.style.display = x1 >= 1 || x2 >= 1 || x3 >= 1 ? "block" : "none";
});
document.getElementById("demo").innerHTML = (x1 || 0);
document.getElementById("demo1").innerHTML = (x2 || 0);
document.getElementById("demo2").innerHTML = (x3 || 0);
}
document.getElementById('Toggle').onclick = toggle;
<div class="problem">
<div class="row">
<div class="col-3">
<form>
<input type="number" id="mySelect" name="mySelect" autocomplete="off" style="width: 3em;"> Sausage
<br>
</form>
</div>
<div class="col-3">
<form>
<input type="number" id="mySelect1" name="mySelect1" autocomplete="off" style="width: 3em;"> Pancake
<br>
</form>
</div>
<div class="col-2">
<form>
<input type="number" id="mySelect2" name="mySelect2" autocomplete="off" style="width: 3em;"> Milk
</form>
</div>
<div class="col-4">
</div>
</div>
<div class="row">
<div class="col-12">
<p>
<button type="button" class="button" id="Toggle" onclick="myFunction()">Show Order</button>
</p>
</div>
</div>
</div>
<div class="row display">
<div class="col-12">
<div style="display:none;" class="problem">Please show this to the cashier.</div>
<div style="display:none;" class="problem">
<h2>Hello, they ordered:</h2>
</div>
<div id="item1" style="display:none;" class="problem">
<h2><span style="font-size: xx-large; color: green;" id="demo"></span>x Sausage(s)</h2>
</div>
<div id="item2" style="display:none;" class="problem">
<h2><span style="font-size: xx-large; color: green;" id="demo1"></span>x Pancake(s)</h2>
</div>
<div id="item3" style="display:none;" class="problem">
<h2><span style="font-size: xx-large; color: green;" id="demo2"></span>x Cup of Milk(s)</h2>
</div>
<div style="display:none;" class="problem">
<h2>Thank you</h2>
</div>
<div style="display:none;" class="problem">Please refresh your browser to restart your order</div>
</div>
</div>

You can loop through all the divs with class="problem" and check their input's values. If there's nothing, then don't show it. If it isn't empty, show it.
You can achieve this with var allDivs = querySelectorAll('.problem input'); to get the inputs in the divs (since we know they have class="problem"), and then loop through that and use an if to check allDivs[i].value.
I didn't want to give the code directly, so hopefully this helps answer your question!

Here you are :
`https://jsfiddle.net/1znqk6us/1/`
I've removed onlick event on button because you don't use this, and for loop.

Related

Dynamic input form not submitting

i have a dynamic form which lets you add and remove inputs. The issue is what even though it works visually, when submitting the form i wont get the values from inputs created by the JS function. If you need anything else let me know as this is about the last implementation to the website
Any ideas as to why? i leave my code below
The html:
<div class="form-container" id="form-container">
<div class="title-title">
<h3 class="recipe-pretitle">Recipe for</h3>
<form action="/recipes/create" enctype="multipart/form-data" method="POST">
<div>
<label for="title">
<input name="title" type="text" id="title" placeholder="Name of dish">
</label>
</div>
</div>
<div class="description-container">
<label class="description-label" for="description">A brief description of your dish: <br> (max 80char)</label>
<textarea name="description" type="text" id="description" cols="30" rows="5"></textarea>
</div>
<div class="directions-ingredients-container">
<div id="product-directions">
<div class="label-directions"><label for="directions">Cooking steps.</label></div>
<div class="controls-ol-container">
<div class="controls">
<i class="fa fa-sm">Add step</i>
<i class="fa fa-sm">Remove last step</i>
</div>
<div class="instruction-list-container">
<ol id="instruction-list">
</ol>
</div>
</div>
</div>
<div class="ingredients-container">
<div class="label-ingredients"><label for="Ingredients">Ingredients:</label></div>
<div class="controls-ol-container">
<div class="controls">
<i class="fa fa-sm">Add Ingredient</i>
<i class="fa fa-sm">Remove last Ingredient</i>
</div>
<div class="ingredient-list-container">
<ol id="ingredient-list">
</ol>
</div>
</div>
</div>
</div>
<div class="imageInputContainer">
<label id="image-label" for="image">Choose an image</label>
<input name="image" type="file" id="image">
</div>
<div>
<button type="submit">Upload</button>
</form>
</div>
</div>
Font end JS
var add_more_fields = document.getElementById("add_more_fields")
var remove_fields = document.getElementById("remove_fields")
var directions_container = document.getElementById('product-directions')
var instruction_list = document.getElementById('instruction-list')
add_more_fields.onclick = function () {
var node = document.createElement("li")
var newField = document.createElement('input')
newField.setAttribute('type', 'text')
newField.setAttribute('name', 'directions[]')
newField.setAttribute('placeholder', 'Add Instruction')
node.appendChild(newField)
instruction_list.appendChild(node)
}
remove_fields.onclick = function () {
var input_tags = instruction_list.getElementsByTagName('li')
if (input_tags.length > 1) {
instruction_list.removeChild(input_tags[(input_tags.length) - 1])
}
}
var add_more_fields_ingredients = document.getElementById("add_more_fields_ingredients")
var remove_fields_ingredients = document.getElementById("remove_fields_ingredients")
var ingredient_list = document.getElementById('ingredient-list')
add_more_fields_ingredients.onclick = function () {
var node = document.createElement("li")
var newField = document.createElement('input')
newField.setAttribute('type', 'text')
newField.setAttribute('name', 'Ingredients[]')
newField.setAttribute('placeholder', 'Add Ingredient')
node.appendChild(newField)
ingredient_list.appendChild(node)
}
remove_fields_ingredients.onclick = function () {
var input_tags = ingredient_list.getElementsByTagName('li')
if (input_tags.length > 1) {
ingredient_list.removeChild(input_tags[(input_tags.length) - 1])
}
}
your HTML is not valid, form element is not properly closed, move closing form tag outside button container, and form opening tag a level up
this should work, and now you probably need to modify styles and rearrange some elements, so you need to see to it that the form and HTML is valid, and adapt styles accordingly:
<div class="form-container" id="form-container">
<form action="/recipes/create" enctype="multipart/form-data" method="POST">
<div class="title-title">
<h3 class="recipe-pretitle">Recipe for</h3>
<div>
<label for="title">
<input name="title" type="text" id="title" placeholder="Name of dish">
</label>
</div>
</div>
<div class="description-container">
<label class="description-label" for="description">A brief description of your dish:
<br> (max 80char)</label>
<textarea name="description" type="text" id="description" cols="30" rows="5"></textarea>
</div>
<div class="directions-ingredients-container">
<div id="product-directions">
<div class="label-directions">
<label for="directions">Cooking steps.</label>
</div>
<div class="controls-ol-container">
<div class="controls">
<i class="fa fa-sm">Add step</i>
<i class="fa fa-sm">Remove last step</i>
</div>
<div class="instruction-list-container">
<ol id="instruction-list">
</ol>
</div>
</div>
</div>
<div class="ingredients-container">
<div class="label-ingredients">
<label for="Ingredients">Ingredients:</label>
</div>
<div class="controls-ol-container">
<div class="controls">
<i class="fa fa-sm">Add Ingredient</i>
<i class="fa fa-sm">Remove last Ingredient</i>
</div>
<div class="ingredient-list-container">
<ol id="ingredient-list">
</ol>
</div>
</div>
</div>
</div>
<div class="imageInputContainer">
<label id="image-label" for="image">Choose an image</label>
<input name="image" type="file" id="image">
</div>
<div>
<button type="submit">Upload</button>
</div>
</form>
</div>

I want to add an button onclick function, to add several toasts in javascript

I have a form. And I want to write an onClick function which whenever is clicked, a toast including inputs value appears at the end of the page.
here I wrote a function that produce a toast just on the first click.
function Function1() {
var y = document.getElementsByTagName("select")[0].value;
var z = document.getElementsByTagName("input")[0].value;
var x = document.getElementById("toast1");
x.innerHTML = y + " has a " + z + "<span >×</span>";
x.className = "show";
}
<form class="needs-validation" novalidate>
<h5>Select the owner?</h5>
<div class="form-group col mx-auto" style="width: 80%;">
<label for="validationDefault01" class="sr-only">households</label>
<select
class="custom-select place-holder form-control form-control-lg OwnerName"
style="font-size: 15px;"
id="validationDefault01"
style="border-radius: 2px;"
required
>
<option value="" selected hidden>Choose...</option>
<option value="Jack London"> Jack London</option>
<option value="Sarah London"> Sarah London</option>
<option value="Mike"> Mike</option>
</select>
</div>
<br />
<h5>What is the brand?</h5>
<div class="input-group mx-auto" style="border-radius: 8px; width: 75%;">
<label for="validationCustom01" class="sr-only">Brand</label>
<input
class="form-control brand"
type="text"
required
id="validationCustom01"
style="font-size: 15px; height: 40px;"
placeholder="Brand"
/>
<div class="valid-feedback">correct</div>
</div>
<br />
<h5>What is the model year?</h5>
<div class="input-group mx-auto" style="border-radius: 8px; width: 75%;">
<label for="validationCustom01" class="sr-only">yyyy</label>
<input
class="form-control"
type="text"
required
id="validationCustom01"
style="font-size: 15px; height: 40px;"
onkeypress="return CheckNumeric()"
placeholder="yyyy"
/>
<div class="valid-feedback">correct</div>
</div>
<br />
<h5 class="mx-2">How much is worth?</h5>
<div class="input-group mx-auto" style="border-radius: 8px; width: 75%;">
<div class="input-group-prepend">
<div
class="input-group-text font-weight-bold"
style="
font-size: 15px;
background-color: rgba(50, 157, 105, 1);
color: white;
"
>
$
</div>
</div>
<label for="validationDefault01" class="sr-only">deposite</label>
<input
type="text"
class="form-control floatNumber"
id="validationDefault01"
style="font-size: 15px;"
onkeypress="return CheckNumeric()"
onkeyup="FormatCurrency(this)"
placeholder="example: 10000"
required
/>
</div>
<p id="demo"></p>
<br />
<div class="row">
<div class="col">
<button
class="quebtn1 mx-auto"
style="width: 130px;"
type="button"
onclick="Function1()"
>
Add Vehicle
</button>
</div>
</div>
<div class="row">
<div class="col-6">
<button class="quebtn1 float-right" type="button">Back</button>
</div>
<div class="col-6">
<button class="quebtn1" type="submit">Next</button>
<br />
</div>
<div class="row pt-0 mx-auto text-center">
<div
class="toast-body toast no-gutters"
data-autohide="false"
role="alert"
aria-live="assertive"
aria-atomic="true"
id="toast1"
></div>
</div>
</div>
</form>
But I want when user fill the form and click on "add vehicle" button to add another vehicle again and again, each time a toast including information of the previous vehicle user added, produce.
To understand why you aren't getting the results you're looking for, you have to understand the DOM. Currently, whenever the button is clicked, you are always changing the same DOM element.
var x = document.getElementById("toast1");
x.innerHTML = y + " has a " + z + "<span >×</span>";
x.className = "show";
See how you're selecting the element with the ID of toast1 and manipulating that element every time by setting its innerHTML and className?
What you want to do is create a new element, and place that new element underneath the element with the ID of toast1.
To create an new element, you would use createElement:
var newEl = document.createElement("p");
newEl.innerHTML = y + " has a " + z + "<span >×</span>";
newEl.className = "show";
And then to insert it use appendChild:
x.appendChild(newEl);
Here's the complete code:
function Function1() {
var y = document.getElementsByTagName("select")[0].value;
var z = document.getElementsByTagName("input")[0].value;
var x = document.getElementById("toast1");
var newEl = document.createElement("div");
newEl.innerHTML = y + " has a " + z + "<span >×</span>";
newEl.className = "show";
x.appendChild(newEl);
}
<form class="needs-validation" novalidate>
<h5>Select the owner?</h5>
<div class="form-group col mx-auto" style="width: 80%;">
<label for="validationDefault01" class="sr-only">households</label>
<select
class="custom-select place-holder form-control form-control-lg OwnerName"
style="font-size: 15px;"
id="validationDefault01"
style="border-radius: 2px;"
required
>
<option value="" selected hidden>Choose...</option>
<option value="Jack London"> Jack London</option>
<option value="Sarah London"> Sarah London</option>
<option value="Mike"> Mike</option>
</select>
</div>
<br />
<h5>What is the brand?</h5>
<div class="input-group mx-auto" style="border-radius: 8px; width: 75%;">
<label for="validationCustom01" class="sr-only">Brand</label>
<input
class="form-control brand"
type="text"
required
id="validationCustom01"
style="font-size: 15px; height: 40px;"
placeholder="Brand"
/>
<div class="valid-feedback">correct</div>
</div>
<br />
<h5>What is the model year?</h5>
<div class="input-group mx-auto" style="border-radius: 8px; width: 75%;">
<label for="validationCustom01" class="sr-only">yyyy</label>
<input
class="form-control"
type="text"
required
id="validationCustom01"
style="font-size: 15px; height: 40px;"
onkeypress="return CheckNumeric()"
placeholder="yyyy"
/>
<div class="valid-feedback">correct</div>
</div>
<br />
<h5 class="mx-2">How much is worth?</h5>
<div class="input-group mx-auto" style="border-radius: 8px; width: 75%;">
<div class="input-group-prepend">
<div
class="input-group-text font-weight-bold"
style="
font-size: 15px;
background-color: rgba(50, 157, 105, 1);
color: white;
"
>
$
</div>
</div>
<label for="validationDefault01" class="sr-only">deposite</label>
<input
type="text"
class="form-control floatNumber"
id="validationDefault01"
style="font-size: 15px;"
onkeypress="return CheckNumeric()"
onkeyup="FormatCurrency(this)"
placeholder="example: 10000"
required
/>
</div>
<p id="demo"></p>
<br />
<div class="row">
<div class="col">
<button
class="quebtn1 mx-auto"
style="width: 130px;"
type="button"
onclick="Function1()"
>
Add Vehicle
</button>
</div>
</div>
<div class="row">
<div class="col-6">
<button class="quebtn1 float-right" type="button">Back</button>
</div>
<div class="col-6">
<button class="quebtn1" type="submit">Next</button>
<br />
</div>
<div class="row pt-0 mx-auto text-center">
<div
class="toast-body toast no-gutters"
data-autohide="false"
role="alert"
aria-live="assertive"
aria-atomic="true"
id="toast1"
></div>
</div>
</div>
</form>
Also, here are some tips that aren't directly related to your question:
There's also querySelector instead of stuff like getElementsByTagName. It lets you basically use CSS selectors to select elements, which a lot of people find easy to use.
For this sort of DOM manipulation, you also might want to try using the jQuery library
It's good to learn how DOM manipulation works for educational purposes, but on real projects the field has moved towards UI libraries like React and Vue.
You named your function Function1. This works, but it's better if you could name it something more descriptive, like addVehicle. That way it's more clear what it's doing. With one function Function1 is probably fine, but imagine if you had 12 functions and had to think to yourself, "Wait, what is Function3 doing again? Did I want to use Function7?"
It's good to learn by doing, but it's also good to mix that with a more "bottom up" approach of reading books and stuff to give you the foundation you'll need for fun projects like this.

Collect input value based on button element hierarchy position

My actual html code:
<div class="panel panel-primary">
<div class="panel-heading">
Informação Pessoal
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Nome</span>
<input type="text" name="adminName" class="form-control" value="<?php echo $adminData->name; ?>">
</div>
</div>
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Email</span>
<input type="text" name="adminEmail" class="form-control" value="<?php echo $adminData->email; ?>">
</div>
</div>
<div class="col-xs-12" style="margin-top: 2%; margin-bottom: 2%;">
<button type="button" class="btn btn-success pull-right" id="savePersInfo">Guardar Alteração</button>
</div>
</div>
</div>
I have multiple such panels, each one with a button that has specific ID. My goal is to collect all the input within the panel that the button was pressed. Although this sounds easy, my MAIN goal is to reuse the same function on multiple pages that have multiple panels (since the structures is simillar), to then use ajax to update the information. The only thing that I would need to provide the function is the id of the button so it can find automatically the relative input.
I am trying to accomplish this in vanilla js, though im ok with jquery.
My actual js code:
document.getElementById('savePersInfo').onclick = function(){
var inputArray = ['adminName', 'adminEmail'];
console.log(collectInfo(inputArray));
};
function collectInfo(inputArray){
$inputValueArray = []
for(var c = 0; c < inputArray.length; c++){
$inputValueArray[c] = document.querySelectorAll('[name="' + inputArray[c] + '"]')[0].value;
}
return $inputValueArray;
}
As you see here I need to specify the name of the input to be able to retrieve it, what I want is not to do that and have JS find it automatically based on the panel is was clicked on.
Any suggestions/ideas on how this can be accomplished ?
ps: ignore the inline styling and other layout stuff, early development phase.
You can use either javasscript's closest() or jQuery's closest(), and with those find the closest element being ancestor to both the button and input's, e.g. panel-body.
From there you then simply use that element as starting point, e.g. with javascript element.querySelectorAll), and select all inputs and grab their value.
Note, if to use the javascript version and support IE (it doesn't know of closest()), you can make use of the "polyfill" I added at the end.
Updated based on a comment, where I added a checkbox and select to my "javascript" code sample to show it works with those too, and how to get the button id.
Stack snippet - javascript
document.querySelectorAll('button').forEach( function(btn) {
btn.addEventListener('click', findInputs);
})
function findInputs() {
console.clear();
var button_id = this.id;
this.closest('.panel-body').querySelectorAll('input, select').forEach( function(inp) {
var test_checked = ((inp.type == 'checkbox' && inp.checked) ? ' checked' : '');
console.log(button_id, inp.value + test_checked)
})
}
<div class="panel panel-primary">
<div class="panel-heading">
Informação Pessoal
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Nome</span>
<input type="text" name="adminName" class="form-control" value="name 1">
</div>
</div>
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Email</span>
<input type="text" name="adminEmail" class="form-control" value="email 1">
</div>
</div>
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Test</span>
<input type="checkbox" name="adminTest" class="form-control" value="test 1">
</div>
</div>
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Test 2</span>
<select name="adminTest2" class="form-control">
<option value="Test2-a">Test2-a</option>
<option selected value="Test2-b">Test2-b</option>
<option value="Test2-c">Test2-c</option>
</select>
</div>
</div>
<div class="col-xs-12" style="margin-top: 2%; margin-bottom: 2%;">
<button type="button" class="btn btn-success pull-right" id="savePersInfo">Guardar Alteração</button>
</div>
</div>
</div>
Stack snippet - jQuery
$('button').each( function() {
$(this).click(findInputs);
})
function findInputs() {
$(this).closest('.panel-body').find('input').each( function() {
console.log( $(this).val() );
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel panel-primary">
<div class="panel-heading">
Informação Pessoal
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Nome</span>
<input type="text" name="adminName" class="form-control" value="name 1">
</div>
</div>
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Email</span>
<input type="text" name="adminEmail" class="form-control" value="email 1">
</div>
</div>
<div class="col-xs-12" style="margin-top: 2%; margin-bottom: 2%;">
<button type="button" class="btn btn-success pull-right" id="savePersInfo">Guardar Alteração</button>
</div>
</div>
</div>
<hr>
<div class="panel panel-primary">
<div class="panel-heading">
Informação Pessoal 2
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Nome</span>
<input type="text" name="adminName" class="form-control" value="name 2">
</div>
</div>
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Email</span>
<input type="text" name="adminEmail" class="form-control" value="email 2">
</div>
</div>
<div class="col-xs-12" style="margin-top: 2%; margin-bottom: 2%;">
<button type="button" class="btn btn-success pull-right" id="savePersInfo2">Guardar Alteração 2</button>
</div>
</div>
</div>
Add javascript closest() support for IE9+
if (!Element.prototype.matches)
Element.prototype.matches = Element.prototype.msMatchesSelector ||
Element.prototype.webkitMatchesSelector;
if (!Element.prototype.closest)
Element.prototype.closest = function(s) {
var el = this;
if (!document.documentElement.contains(el)) return null;
do {
if (el.matches(s)) return el;
el = el.parentElement || el.parentNode;
} while (el !== null && el.nodeType === 1);
return null;
};
Src: https://developer.mozilla.org/en-US/docs/Web/API/Element/closest
You can use Element.closest() on the element with the passed id to target the panel you are looking for. Then use Array.prototype.map() to return the value of all inputs from the selected panel.
Try the following way:
document.getElementById('savePersInfo').onclick = function(){
console.log(collectInfo(this.id));
};
function collectInfo(id){
var panel = document.getElementById(id).closest(".panel.panel-primary")
var $inputValueArray = [...panel.querySelectorAll('input[type=text]')].map(i => i.value);
return $inputValueArray;
}
<div class="panel panel-primary">
<div class="panel-heading">
Informação Pessoal
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Nome</span>
<input type="text" name="adminName" class="form-control" value="John Michale Kane">
</div>
</div>
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Email</span>
<input type="text" name="adminEmail" class="form-control" value="john#gmail.com">
</div>
</div>
<div class="col-xs-12" style="margin-top: 2%; margin-bottom: 2%;">
<button type="button" class="btn btn-success pull-right" id="savePersInfo">Guardar Alteração</button>
</div>
</div>
</div>

How to change id value iterating by class

I have this html:
<div class="info">
<div class="form-group">
<label class="control-label col-sm-2">Title</label>
<div class="col-xs-10 col-sm-8">
<input id="titleInfo" class="form-control" type="text" placeholder="Title">
</div>
<div class="col-xs-1 col-sm-1">
<button class="btn btn-default remove_field"><i class="fa fa-remove"></i></button>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Text</label>
<div class="col-xs-10 col-sm-8">
<textarea id="textInfo" class="form-control" type="text" placeholder="..."></textarea>
</div>
</div>
</div>
Into my jsp I have many of this:
<div class="info">
...
</div>
<div class="info">
...
</div>
<div class="info">
...
</div>
Now, I would change the id tags: titleInfo and textInfo of every div with class info in ascending order.
<div class="info">
..<input id="titleInfo1"..
..<textarea id="textInfo1"..
</div>
<div class="info">
..<input id="titleInfo2"..
..<textarea id="textInfo2"..
</div>
<div class="info">
..<input id="titleInfo3"..
..<textarea id="textInfo3"..
</div>
and so on.
I thought to iterate by class info:
var x = 1;
$(".info").each(function() {
//Now, I don't know how to change the ids
x++;
});
You need to update the code to following
var x = 1;
$(".info").each(function() {
var elems = $(this).find(".form-control"); // get all the input elements with class form-control
elems.each(function() { // iterate over the elements
$(this).attr("id", $(this).attr("id") + x); // update id
});
x++;
});
Update
var x = 1;
$(".info").each(function() {
var elems = $(this).find(".form-control"); // get all the input elements with class form-control
$(elems[0]).attr("id", "titleInfo" + x);
$(elems[1]).attr("id", "textInfo" + x);
x++;
});
You should really do this server side, within the loop control you have that generates those blocks. For the sake of answering, here you go.
$(".info").each(function(index) {
var $title = $(this).find("#titleInfo");
var $text = $(this).find("#textInfo");
$title[0].id += (index+1);
$text[0].id += (index+1);
});
Take a look at this demo as well.
Find the below code snippet.
var x = 1;
$(".info").each(function() {
var ele=$(this).find('.form-control');
ele.each(function(){
setId($(this),x)
})
x++;
});
function setId(ele,x){
ele.attr('id',ele.attr('id')+x)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div class="info">
<div class="form-group">
<label class="control-label col-sm-2">Title</label>
<div class="col-xs-10 col-sm-8">
<input id="titleInfo" class="form-control" type="text" placeholder="Title">
</div>
<div class="col-xs-1 col-sm-1">
<button class="btn btn-default remove_field"><i class="fa fa-remove"></i></button>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Text</label>
<div class="col-xs-10 col-sm-8">
<textarea id="textInfo" class="form-control" type="text" placeholder="..."></textarea>
</div>
</div>
</div>
This also does the same.
Script
var x = 1;
$(".info").each(function() {
var ele=$(this).find('.form-control');
ele.each(function(){
$(this).attr('id',$(this).attr('id')+x)
})
x++;
});

how can i call each value in one function?

when i calculate each price the problem is insert both.
I just want each price for pickup and delivery
Javascript
function refreshprices() {
var pickup_td = getDistanceFromLatLonInKm(origin_lat,origin_lng,pickup_lat,pickup_lng);
var pickup_cost = calculatePrice(base_cost, base_dist, additional_cost, additional_dist, pickup_td);
var pickup_output = document.getElementById('pickup_price');
pickup_output.innerHTML = " $ " + pickup_cost;
var delivery_td=getDistanceFromLatLonInKm(origin_lat,origin_lng,delivery_lat,delivery_lng);
var delivery_cost=calculatePrice(base_cost, base_dist, additional_cost, additional_dist, delivery_td);
var delivery_output = document.getElementById('delivery_price');
delivery_output.innerHTML = " $ " + delivery_cost;
}
HTML
<form action="#" method="post">
<div id="pickup_option_calculate_price">
<div class="row-fluid">
<div class="span12" >
<h2>Pickup Option</h2>
<label class="radio">
<div class="option-title"><input type="radio" name="pickup" value="no_pickup" id="type_0" checked>No pickup required</div>
</label>
<div class="option-desc">You must drop off your passports and supporting documents at our office.</div>
<label class="radio">
<div class="option-title"><input type="radio" name="pickup" value="pickup" id="type_1">Pickup required ( <span id="pickup_price"> Enter Address to calculate Price </span>)</div>
</label>
<div class="option-desc">We will pickup the passports and supporting documents from your home or office.</div>
</div>
</div>
<div id="pickup_location">
<div class="row-fluid">
<input type="text" name="address" class="span10">
<input type="button" name="search" class="span2" value="Calculate Price" class="btn">
</div>
<div class="row-fluid">
<div class="span12">
<div id="coords" style="margin-top: 10px;"></div>
<div id="gmap" style="height:200px;position: relative; background-color: rgb(229, 227, 223); overflow: hidden;"></div>
</div>
</div>
</div>
</div>
<div id="delivery_option_calculate_price">
<div class="row-fluid">
<div class="span12" >
<h2>delivery Option</h2>
<label class="radio">
<div class="option-title"><input type="radio" name="delivery" value="no_delivery" id="type_0" checked>No delivery required</div>
</label>
<div class="option-desc">You must drop off your passports and supporting documents at our office.</div>
<label class="radio">
<div class="option-title"><input type="radio" name="delivery" value="delivery" id="type_1">delivery required ( <span id="delivery_price"> Enter Address to calculate Price </span>)</div>
</label>
<div class="option-desc">We will delivery the passports and supporting documents from your home or office.</div>
</div>
</div>
<div id="delivery_location">
<div class="row-fluid">
<input type="text" name="delivery_address" class="span10">
<input type="button" name="delivery_search" class="span2" value="Calculate Price" class="btn">
</div>
<div class="row-fluid">
<div class="span12">
<div id="coords" style="margin-top: 10px;"></div>
<div id="gmap" style="height:200px;position: relative; background-color: rgb(229, 227, 223); overflow: hidden;"></div>
</div>
</div>
</div>
</div>
</form>
when i calculate each price the problem is insert both.
I just want each price for pickup and delivery
Image is below.
Ok.Now i found it all my brother.
refreshprices();
pickup_output = document.getElementById('pickup_price');
pickup_output.innerHTML = " $ " + pickup_cost;
refreshprices();
var delivery_output = document.getElementById('delivery_price');
delivery_output.innerHTML = " $ " + delivery_cost;
function refreshprices() {
var pickup_td = getDistanceFromLatLonInKm(origin_lat,origin_lng,pickup_lat,pickup_lng);
pickup_cost = calculatePrice(base_cost, base_dist, additional_cost, additional_dist, pickup_td);
var delivery_td=getDistanceFromLatLonInKm(origin_lat,origin_lng,delivery_lat,delivery_lng);
delivery_cost=calculatePrice(base_cost, base_dist, additional_cost, additional_dist, delivery_td);
}

Categories