jQuery - Sending "Select All" Check boxes with Multiple Forms - javascript

I have checked online for a solution to pass my values for the checkbox "select all". I have multiple forms in a page. So I will need to separate passing the values based on specific forms.
jQuery:
$(document).ready(function() {
$(".select-all").change(function () {
$(this).siblings().prop('checked', $(this).prop("checked"));
});
})
HTML for form:**
<div class="col">
<fieldset>
<form action="{$link->getLink('controller')|escape:'htmlall':'utf-8'}" method="post">
<p>
{foreach from=$payment item=row}
<input type="checkbox" name="payment[]" maxlength="50" value={$row.id_order}>
<label> ID: <b>{$row.id_order}</b></label><br/>
{/foreach}
<br/>
<input id="submit" name="submitpayment" type="submit" value="PACK ITEMS" class="button" />
</p>
</form>
</fieldset>
</div>
Error (Value is empty):
input type="checkbox" class="select-all" name="payment[]" value=""
SQL query to pass records:
public function displayOrdersbyID()
{
$query1 = new DbQuery();
$query1->select('o.id_order')
->from('orders','o')
->leftJoin('carrier','c','o.id_carrier=c.id_carrier')
->leftJoin('order_state_lang','s','o.current_state=s.id_order_state')
->where('c.name = ' . "'XXX'")
->where('s.name = ' . "'Payment accepted'");
$payment = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query1);
$this->context->smarty->assign( 'payment', $payment);
Controller:
if (Tools::isSubmit('submitpayment')) {
$ids= Tools::getValue('payment');
$query18 = new DbQuery();
$query18->select('id_order_state')
->from('order_state_lang')
->where('name = ' . "'Processing in progress'");
$updateinprogress = Db::getInstance()->getValue($query18);
foreach ($ids as $updateids) {
$objOrder = new Order($updateids);
$history = new OrderHistory();
$history->id_order = (int)$objOrder->id;
$history->id_employee = $cookie->id_employee;
$history->changeIdOrderState($updateinprogress, (int)($objOrder->id));
$history->add(true);
$history->save();
}
}
SELECT ALL checkbox:
<input type="checkbox" class="select-all" name="payment[]" value=
{$row.id_order}>
<label> SELECT ALL</label>
I was using the above code to create a SELECT ALL checkbox for the form, placing it outside the loop. I understand it is wrong and value is not passing, where should I place the checkbox at?
Any guidance is appreciated.
Thank you.

I think the problem in select-all value because there no initialization for $row.id_order in
<input type="checkbox" class="select-all" name="inprogress[]" value={$row.id_order}>
But if you assign the value of $row.id_order then might be not used in the following child like the {foreach from=$payment item=row} must use another variable identifier then row.
you working with a wrong practice you can't assign $row.order_id outside the loop.If there you want to use these element value in PHP then no need to do anything the $_POST['payment'] for the second form and $_POST['inprogress'] will return the value you want.
if no checkbox is selected then the result is returned blank.
and remember this will return an array type object.

The line
<input type="checkbox" class="select-all" name="inprogress[]" value={$row.id_order}>
lies outside the loop. Thus the value of {$row.id_order} will not be defined in your template. Check the DOM tree for compiled value.
And what is your final goal with the SELECT ALL button ? Is there any relation between the two forms?
Edit:
See the value of output variable. You can collect this value and pass it along with form submission.
<div class="col">
<fieldset>
<form>
<p>
<input type="checkbox" class="select-all" name="payment[]" value="22">
<label> SELECT ALL</label>
<br/><br/>
<input type="checkbox" name="payment[]" maxlength="50" value="a">
<label> ID: <b>A</b></label><br/>
<input type="checkbox" name="payment[]" maxlength="50" value="b">
<label> ID: <b>B</b></label><br/>
<input id="submit" name="submitinprogress" type="submit" value="PACK ITEMS" class="button" />
</p>
</form>
</fieldset>
</div>
$(document).ready(function() {
$(".select-all").change(function () {
$(this).siblings().prop('checked', $(this).prop("checked"));
let inputs = $(this).siblings("input[type=checkbox]");
let output = [];
for(let i = 0; i < inputs.length; i++){
output.push(inputs[i].value);
};
console.log(output); // ["a", "b"]
});
});

Related

How to capture a check box input element in Java script?

<form name="formname">
<input type="text" maxlength="100" name="user_name" id="user_input"></input>
<input type="checkbox" name="website_response[]" value="I really like your site" id="checkbox">I like your site</input>
<input type="checkbox" name="website_response[]" value="One of the best site">One of the best site</input>
<input type="checkbox" name="website_response[]" value="good site">Good Site</input>
<input type="checkbox" name="website_response[]" value="I wish my site were good">I wish my site were good</input>
</form>
The above code conatins name attribute as an array. How do I access it in Javascript?
You can access the name attribute of the checkboxes using the following :
var checkboxes = document.querySelectorAll("input[type=checkbox]");
var names = [];
checkboxes.forEach(elem => {
names.push(elem.name);
});
If you only want the name attribute of the checkbox which is checked you can use :
var checkboxes = document.querySelectorAll("input[type=checkbox]");
var names = [];
checkboxes.forEach(elem => {
if(elem.checked) {
names.push(elem.name);
}
});

Store input radio selections when submit is clicked

I need to store in my js file which radio option for each radio name was selected as well as store the Username that was entered. Here is my form
<form id="newPlayer">
Username:<br>
<input type="text" name="user"/><br>
Please Choose a Class: <br>
<input type="radio" name="class"/>Archer
<input type="radio" name="class"/>Mage
<input type="radio" name="class"/>Warrior
<br>
Please Choose a Race: <br>
<input type="radio" name="race"/>Orc
<input type="radio" name="race"/>Elf
<input type="radio" name="race"/>Human
<input type="radio" name="race"/>Worg
<br>
<input type="submit" value="Submit">
</form>
EDIT:
When I try to target the submit button for a click function it causes my page to reload instead of making the form fadeOut
var userInput;
var classInput;
var raceInput;
$('input[type=submit]').click(function(){
$('#newPlayer').fadeOut(500);
userInput = $('input[name="user"]').val();
classInput = $('input[name="class"]:checked').val();
raceInput = $('input[name="race"]:checked').val();
});
Maybe this helps. First, you will have to put values on those inputs
<form id="newPlayer">
Username:<br>
<input type="text" name="user"/><br>
Please Choose a Class: <br>
<input value="archer" type="radio" name="class"/>Archer
<input value="mage" type="radio" name="class"/>Mage
<input value="warrior" type="radio" name="class"/>Warrior
<br>
Please Choose a Race: <br>
<input value="orc" type="radio" name="race"/>Orc
<input value="elf" type="radio" name="race"/>Elf
<input value="human" type="radio" name="race"/>Human
<input value="worg" type="radio" name="race"/>Worg
<br>
<input type="submit" value="Submit">
</form>
Then, using jQuery, a simple .val() will do the job:
var class_val = $('input[name="class"]:checked').val();
var race = $('input[name="race"]:checked').val();
var user = $('input[name="user"]').val();
After that, you just need to put in localStorage
localStorage.setItem('class', class_val);
localStorage.setItem('race', race);
localStorage.setItem('user', user);
To access those values in the future, you do that
var stored_class = localStorage.getItem('class');
var stored_race = localStorage.getItem('race');
var stored_user = localStorage.getItem('user');
To make things happens on submit, you add an submit event to the form, like that:
$('form').on('submit', function() {
// Get values
var class_val = $('input[name="class"]:checked').val();
...
// Store values
localStorage.setItem('class', class_val);
...
// Avoid form submit
return false;
});
Hope it helps :)
I think I would use localStorage.
For example:
//Make sure to set the selection variable to a object that contains the selections made by the user.
function save() {
//This will save the current settings as an object to the localStorage.
localStorage.selections = JSON.stringify(selections) ;
}
function load() {
if (!localStorage.selections) {
alart("No saves found.") ;
return false ;
}
selections = JSON.parse(localStorage.selections) ;
}
Read more about localStorage here.

javascript .push method inside .each loop only returning one array

Im trying iterate over the checkbox groups and if each group has at least one box checked, I want to add that product information to an array(upperOrder). The problem with my code is that it's only adding the last checked checkbox group (or over writing the previous added group).
Basically I want a multidimensional array with the main array being upperOrder and the sub arrays being each product's information.
Thanks and appreciate anyone's help or if there is a better method to accomplishing this, I would appreciate any suggestions!
html:
<form class="upperCheckboxForm" data-prodid="100" data-prodname="adams" id="group1">
<fieldset data-role="controlgroup">
<legend>Group 1:</legend>
<input type="checkbox" name="checkbox-v-2a" id="checkbox-v-2a" value="one" data-tooth-position="UR1">
<label for="checkbox-v-2a">One</label>
<input type="checkbox" name="checkbox-v-2b" id="checkbox-v-2b" value="two" data-tooth-position="UR2">
<label for="checkbox-v-2b">Two</label>
<input type="checkbox" name="checkbox-v-2c" id="checkbox-v-2c" value="three" data-tooth-position="UR3">
<label for="checkbox-v-2c">Three</label>
</fieldset>
</form>
<form class="upperCheckboxForm" data-prodid="101" data-prodname="lap" id="group2">
<fieldset data-role="controlgroup">
<legend>Group 2:</legend>
<input type="checkbox" name="checkbox-v-2a" id="checkbox-v-2a" value="four" data-tooth-position="UR4">
<label for="checkbox-v-2a">Four</label>
<input type="checkbox" name="checkbox-v-2b" id="checkbox-v-2b" value="five" data-tooth-position="UR5">
<label for="checkbox-v-2b">Five</label>
<input type="checkbox" name="checkbox-v-2c" id="checkbox-v-2c" value="six" data-tooth-position="UR6">
<label for="checkbox-v-2c">Six</label>
</fieldset>
</form>
<button id="submitPrintForm">Click</button>
jquery:
$('#submitPrintForm').on('click', function() {
var upperOrder = [];
$('.upperCheckboxForm').each(function() {
var $prodName = $(this).data('prodname'),
$prodId = $(this).data('prodid'),
$prodUrl = $(this).attr('id'),
$prodPosition = [];
$('#'+ $prodUrl +' input:checked').each(function() {
$prodPosition.push($(this).data('tooth-position'));
})
if($prodPosition.length > 0) {
upperOrder.push = ([$prodName, $prodId, $prodPosition.length, $prodPosition]);
}
})
console.log(upperOrder);
});
push is a method. Call it like this:
upperOrder.push([$prodName, $prodId, $prodPosition.length, $prodPosition])
when you are assigning something to upperOrder.push you are actually overwriting the method push, which will make subsequent calls to it fail.
Is this what yyou were lookin for?
$('#submitPrintForm').on('click', function() {
var upperOrder = [];
$('.upperCheckboxForm').each(function() {
var $prodName = $(this).data('prodname'),
$prodId = $(this).data('prodid'),
$prodUrl = $(this).attr('id'),
$prodPosition = [];
$('input:checked', this).each(function() {
$prodPosition.push($(this).data('tooth-position'));
})
if($prodPosition.length > 0) {
upperOrder.push($prodName, $prodId, $prodPosition.length, $prodPosition);
}
})
console.log(upperOrder);
});

Javascript adding values to radio buttons to input price

Im trying to create a javascript block inside of a webpage im working on. I havent done javascript since highschool and it doesnt seem to want to come back to me :(
In this block of code i want to have 4 sets of radio buttons, each time a selection is picked,
a price will be inputed to a variable for each radio group. i.e
var firstPrice = $25
var secondPrice = $56
var thirdPrice = $80
var fourthPrice = $90
then after each radio group has one selection there will be a function attached to the submit button that adds up each price to display the final amount inside of a hidden field
var totalPrice = (firstPrice + secondPrice + thirdPrice + fourthPrice)
My question is, how do i attach a number value to a radio button within a group, same name but id is different in each group. Then do i just create a function that adds all the price groups up and then set the submit button to onClick = totalPrice();
Here is an example of one set of radio buttons:
<label>
<input type="radio" name="model" value="radio" id="item_0" />
item 1</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_1" />
item2</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_2" />
item3</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_3" />
Item4</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_4" />
item5</label>
</form>
then my script looks something like:
function finalPrice90{
var selectionFirst = document.modelGroup.value;
var selectionSecond = document.secondGroup.value;
var selectionThird = document.thirdGroup.value;
var selectionFourth = document.fourthGroup.Value;
var totalPrice = (selectionFirst + selectionSecond + selectionThird + selectionFourth);
}
Try this fiddle
http://jsfiddle.net/tariqulazam/ZLQXB/
Set the value attribute of your radio inputs to the price each radio button should represent.
When it's time to calculate, simply loop through each group and get the value attribute if the checked radio.
Because the value attribute is a string representation of a number, you'll want to convert it back to a number before doing any math (but that's a simple parseInt or parseFloat).
Here's a working fiddle using pure JavaScript: http://jsfiddle.net/XxZwm/
A library like jQuery or Prototype (or MooTools, script.aculo.us, etc) may make this easier in the long run, depending on how much DOM manipulation code you don't want to re-invent a wheel for.
Your requirements seem pretty simple, here's an example that should answer most questions. There is a single click listener on the form so whenever there is a click on a form control, the price will be updated.
<script type="text/javascript">
//function updatePrice(el) {
function updatePrice(event) {
var el = event.target || event.srcElement;
var form = el.form;
if (!form) return;
var control, controls = form.elements;
var totalPrice = 0;
var radios;
for (var i=0, iLen=controls.length; i<iLen; i++) {
control = controls[i];
if ((control.type == 'radio' || control.type == 'checkbox') && control.checked) {
totalPrice += Number(control.value);
}
// Deal with other types of controls if necessary
}
form.totalPrice.value = '$' + totalPrice;
}
</script>
<form>
<fieldset><legend>Model 1</legend>
<input type="radio" name="model1" value="25">$25<br>
<input type="radio" name="model1" value="35">$35<br>
<input type="radio" name="model1" value="45">$45<br>
<input type="radio" name="model1" value="55">$55<br>
</fieldset>
<fieldset><legend>Model 2</legend>
<input type="radio" name="model2" value="1">$1<br>
<input type="radio" name="model2" value="2">$2<br>
<input type="radio" name="model2" value="3">$3<br>
<input type="radio" name="model2" value="4">$4<br>
<fieldset><legend>Include shipping?</legend>
<span>$5</span><input type="checkbox" value="5" name="shipping"><br>
</fieldset>
<input name="totalPrice" readonly><br>
<input type="reset" value="Clear form">
</form>
You could put a single listener on the form for click events and update the price automatically, in that case you can get rid of the update button.

binding events triggered by multiple input fields

what are the best practices to binding events triggered by multiple input fields which are dependent on each other in jquery?
For eg: lets take a search engine which searches for students based on what is entered and selected in the fields below.
1. text boxes
2. select lists
3. select boxes
4. option buttons
Without a button which will trigger these events, what is the best way to achieving the following:
Displaying search result as soon as user enters or selects values in one of the input fields and refines the search as users enters or selects values in other fields options.
Displaying search result only after each fields has a valid value.
Any input would be appretiated.
I've put this together this jsFiddle http://jsfiddle.net/VJwpv/1/.
If you are looking at doing validation with JavaScript then I'd recommend you look into this jQuery Validation plugin
HTML
<div id="searchForm">
<input id="textBox" class="searchField" type="text" />
<select id="dropDown" class="searchField">
<option value="Option1">Option1</option>
<option value="Option2">Option2</option>
</select>
<input id="checkbox1Value" type="checkbox" name="checkbox" value="Checkbox1" />Checkbox1
<input id="checkbox2Value" type="checkbox" name="checkbox" value="Checkbox2" />Checkbox2
<input type="radio" name="radio" value="Radio1" /> Radio1
<input type="radio" name="radio" value="Radio2" /> Radio2
</div>
<div id="results"></div>
JavaScript
function validateForm() {
// if valid
return true;
// else return false
}
function performSearch() {
var textBoxValue = $("#textBox").val();
var dropDownValue = $("#dropDown").val();
var checkbox1Value = $("#checkbox1Value").is(":checked");
var checkbox2Value = $("#checkbox2Value").is(":checked");
var radioValue = $("input:radio[name=radio]:checked").val();
// What you'd actually do here is an AJAX call to get the search results
// and pass all the values defined above in the request
$("#results").html("Textbox: " + textBoxValue + ". Dropdown: " + dropDownValue + ". Checkbox1: " + checkbox1Value + ". Checkbox2: " + checkbox2Value + ". Radio: " + radioValue);
}
function onChange() {
if (validateForm()) {
performSearch();
}
}
$(document).ready(function() {
$("#searchForm input, #searchForm select").change(function() {
onChange();
});
});​
Just give them all a common class name, and bind the change event using a class selector:
HTML:
<input type="text" class="search-field" />
<input type="text" class="search-field" />
<select class="search-field" ><option>1</option><option>2</option></select>
<input type="radio" class="search-field" />
JS:
$('.search-field').change(function() {
// validate all search field values
// display search results based on values
// if search results already shown, filter based on $(this).val()
});
If you have many of these fields, rather than having a handler be bound to each one (as the above code accomplishes), you would get better performance by using a delegated event handler:
HTML:
<div id='parent'>
<input type="text" class="search-field" />
<input type="text" class="search-field" />
<select class="search-field" ><option>1</option><option>2</option></select>
<input type="radio" class="search-field" />
</div>
JS:
$('#parent').on('change', '.search-field', function() {
// validate all search field values
// display search results based on values
// if search results already shown, filter based on $(this).val()
});

Categories

Resources