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()
});
Related
i am submitting data through FormData and i am trying to alert values of check boxes which are checked in my form, right now i am able to make it work for only one check box.
how can i alert values of all those check boxes which are checked.
var formData = new FormData(document.getElementById("update-form"));
$("#myCheckbox1").on('change',function(){
if($("#myCheckbox1").is(':checked'))
$('#hiddenInput1').val(1);
else{
$('#hiddenInput1').val(0);
}
});
alert(
$('#hiddenInput1').val()
);
Check Box 1:
<input type="hidden" value="0" name="visa" id="hiddenInput1">
<input type="checkbox" value="1" id="myCheckbox1">
Example Check Box 2:
<input type="hidden" value="0" name="visa1" id="hiddenInput2">
<input type="checkbox" value="1" id="myCheckbox2">
How to Alert Values of all check boxes which are checked in FormData without repeating code. i found similar example online but none were using FormData.
Form Name is : update-form
You can make use of start with attribute selector to select all checkboxes having id start with myCheckbox and attach it to change event handler.
Inside handler, you can read if checkbox is checked or not and change value of hidden input which is placed before checkbox.
See below code
$(function(){
$("input[type=checkbox][id^=myCheckbox]").on('change',function(){
var isChecked = $(this).is(':checked');
var $hiddenInput = $(this).prev('input[type=hidden]');
if(isChecked)
$hiddenInput.val(1);
else{
$hiddenInput.val(0);
}
alert($hiddenInput.val());
});
//iterate all hidden input on form submit
$('#update-form').submit(function(){
$('input[id^=hiddenUnput]').each(function(){
alert($(this).val());
});
$(this).submit();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Exammple Check Box 1:
<input type="hidden" value="0" name="visa" id="hiddenInput1">
<input type="checkbox" value="1" id="myCheckbox1">
Example Check Box 2:
<input type="hidden" value="0" name="visa" id="hiddenInput2">
<input type="checkbox" value="1" id="myCheckbox2">
I have a select dropdown menu, The user selects one of the options then the related form inputs are shown.
Here is the html:
<select id="relative" name="relative">
<option>Select relative</option>
<option value="father">father</option>
<option value="mother">mother</option>
<option value="brother">brother</option>
</select>
<div id="relative_sections">
<div id="father">
<input type="text" id="father_name" name="father_name" placeholder="Name" />
<input type="email" id="father_email" name="father_email" placeholder="Email" />
<input type="number" id="father_phone" name="father_phone" placeholder="phone" />
</div>
<div id="mother">
<input type="text" id="mother_name" name="mother_name" placeholder="Name" />
<input type="email" id="mother_email" name="mother_email" placeholder="Email" />
<input type="number" id="mother_phone" name="mother_phone" placeholder="phone" />
</div>
<div id="brother">
<input type="text" id="brother_name" name="brother_name" placeholder="Name" />
<input type="email" id="brother_email" name="brother_email" placeholder="Email" />
<input type="number" id="brother_phone" name="brother_phone" placeholder="phone" />
</div>
</div>
CSS code for hiding all the sections:
#mother,
#father,
#brother{
display:none;
}
Javascript code to show/hide sections on changing selected option:
<script type="text/javascript">
function hideAllChildrenButOne(parentId, toRevealId) {
var children = document.getElementById(parentId).children;
for (var i=0; i<children.length; i++) children[i].style.display="none";
document.getElementById(toRevealId).style.display="block";
}
document.getElementById('relative').addEventListener('change', function(){
if (this.value !== '') {
hideAllChildrenButOne('relative_sections', this.value);
}else{
var children = document.getElementById('relative_sections').children;
for (var i=0; i<children.length; i++) children[i].style.display="none";
}
});
</script>
Here is a live fiddle to see what is going on: http://jsfiddle.net/38db59cx
Then I validate the inputs depending on the selected value:
if($_POST['relative'] == 'father'){
//Validate the inputs
}elseif($_POST['relative'] == 'mother'){
//Validate the inputs
}elseif($_POST['relative'] == 'brother'){
//Validate the inputs
}
What I want do is to give the user the ability to select more than one option like ('father' and 'mother') or even all of them then I validate all, But he must at least fill one option data.
How to do this so the user at least select one option, fills the inputs for this option and still could select another option, So that I can validate what he selects?
Most important thing is that the user should select at least one and fill the related ata and can also select more than one.
You could change your select box to either a multiple select or checkboxes. If using checkboxes you would set the name to name='relative[].
Checkboxes:
<label>father<input type="checkbox" name="relative[]" value="father"></label>
<label>mother<input type="checkbox" name="relative[]" value="mother"></label>
<label>brother<input type="checkbox" name="relative[]" value="brother"></label>
MultiSelect
<select name="relative" multiple>
Then in php you can read the data like this:
// create a container to hold the validated results
$aRelative = array();
// if post data exists proceed to check the resutls
if(isset($_POST['relative'])){
// loop over each post value
foreach($_POST['relative'] as $iPos => $a){
// do some validation on the result
if($a != ""){
$aRelative[] &= $a;
}
}
}
if(!empty($aRelative)){
//do whatever with the data
}
So to my understanding, you want user to select multiple option and want to validate them as well. So here is the piece of code which I am sharing. You need to use attribute 'multiple' in your select tag for multiple options to get selected. Here it is:
Click here and check the code, you want to do something similar
In the javascript, you can do something this and add validation for the options.
$('#RNA').submit(function(){
var options = $('#sampleMut > option:selected');
if(options.length == 0){
alert('no value selected');
return false;
}
});
Note: To select more than one option you need to do => press command/CTRL + click options.
Hope it helps a little!
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"]
});
});
I'm trying to add the values of any checked checkbox to an input text field.
Here's my fiddle: http://jsfiddle.net/Lf6ky/
$(document).ready(function() {
$(":checkbox").on('click', function() {
if ($(':checkbox:checked')) {
var fields = $(":checkbox").val();
jQuery.each(fields, function(i, field) {
$('#field_results').val($('#field_results').val() + field.value + " ");
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" id="field_results" /><br>
<input type="checkbox" value="1">1<br>
<input type="checkbox" value="2">2<br>
<input type="checkbox" value="3">3
In this example, I have 3 checkboxes, with the values 1,2,3. If I click on all these checkboxes, then the input field should look like this: 1 2 3
If I uncheck any of these checkboxes, then that corresponding value should disappear in the input field.
How do I do this?
I've stored the collection of check-boxes in a variable $checks, then attach the handler to this collection. Inside the event handler, I take the collection once again and filter (return) only the check-boxes that are checked.
map() returns a jQuery object containing the values of the checked check-boxes, get() converts it to a standard array. Join those values with a space and put 'em in the input.
$(document).ready(function(){
$checks = $(":checkbox");
$checks.on('change', function() {
var string = $checks.filter(":checked").map(function(i,v){
return this.value;
}).get().join(" ");
$('#field_results').val(string);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="field_results"/><br>
<input type="checkbox" value="1">1<br>
<input type="checkbox" value="2">2<br>
<input type="checkbox" value="3">3
On click of a checkbox, loop through the checked inputs, append to a string then assign that to your text box:
$(document).ready(function() {
$("input:checkbox").click(function() {
var output = "";
$("input:checked").each(function() {
output += $(this).val() + " ";
});
$("#field_results").val(output.trim());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" id="field_results" /><br>
<input type="checkbox" value="1">1<br>
<input type="checkbox" value="2">2<br>
<input type="checkbox" value="3">3
First issue is
if($(':checkbox:checked')) {
will always be true since it returns a jQuery object and an object is a truthy value. If you were to use the if, you want to check the length. aka if($(':checkbox:checked').length) {
Secondly
var fields = $(":checkbox").val();
returns only the first element's value and it returns any checkbox, not just the checked ones. You want to loop through $(':checkbox:checked')
One way to attack it is to use an each and an array.
$(":checkbox").on('change', function() {
var total = [];
$(':checkbox:checked').each( function(){ //find the checked checkboxes and loop through them
total.push(this.value); //add the values to the array
});
$('#field_results').val(total.join(" ")); //join the array
});
Problem
if($(':checkbox:checked')) will always be true
var fields = $(":checkbox").val(); Will give first checkbox value
You can try this.
$(document).ready(function() {
$(":checkbox").on('click', function() {
var fields = '';
$(":checkbox").each(function() {
if (this.checked) {
fields += $(this).val() + ' ';
}
});
$('#field_results').val($.trim(fields))
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" id="field_results" />
<br>
<input type="checkbox" value="1">1
<br>
<input type="checkbox" value="2">2
<br>
<input type="checkbox" value="3">3
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.