I have following code to get the values of all checked checkboxes. Surprisingly last element of an array comes as a 'Array'.
var selected = [];
$('#checkboxes input:checked').each(function(){
selected.push($(this).attr('value'));
});
Even if only one checkbox is checked, it adds extra element in an array.
Array will be like this:
selected[0]=Dove
selected[1]=Array
What can be the issue with it? I'm unable to find any reason behind this. Can anyone help?
HTML Code
<ul id='checkboxes' class="list-style1">
<?php foreach($brands as $row){ ?>
<span class='checkbox-wrapper' id='<?php echo $brand; ?>'>
<li><input type='checkbox' value='<?php echo $row['brand']; ?>'>
<label for='<?php echo $row['brand']; ?>'><?php echo $row['brand']; ?></label>
</li></span>
<?php } ?>
</ul>
var checkedValues = $('#checkboxes input:checked').map(function() {
return this.value;
}).get();
it will return the selected value of the checkbox in array.
referrence link
Related
With a SELECT query I obtain an array of 7 names, create a dropdown list and each name is a table which is then hidden.
I want to click on the name in the dropdown list and display the table.
I am not receiving any errors but the following code only displays the first table in the array no matter what option is selected. I have little knowledge of javascript and the function has been cobbled together from various queries on the site.
Javascript:
function changeOpt(clicked) {
var x = document.getElementById("optChange");
var optVal = x.options[x.selectedIndex].value;
for(var i =0; i<x.length;i++){
if(optVal = document.getElementById('datath'))
document.getElementById('data').style.display = 'block';
}
}
HTML/PHP:
while($row = mysqli_fetch_array($result))
{
$array = $row;
//echo '<pre>'.print_r($array).'</pre>';
echo '<table id="data" style="display:none;">';
echo '<tr><td>You searched for:</td></tr>';
echo '<tr><th id="datath">'.$row[0].'</th><th>'.$row[1].'</th><th>'.$row[2].'</th>';
echo '</tr>';
echo '</table>';
$option .= '<option value = "'.$row['1'].'">'.$row['1'].'</option>';
}
?>
<form method="post" action="#" id="my_form" >
<select id="optChange" name="opt" onchange="changeOpt(this.id)">
<option><--select a name--></option>
<option><?php echo $option; ?></option>
</select>
<input type="button" name="submit" value="submit" >
</form>
Am I completely off-beam ? Can someone give me some guidance please to get my code straight.
I have input radio list with custom values wich is loaded from the database. By default i have one item checked when window is loaded.
So when i try to grab that checked value i get NULL, but value of checked radio exist.
Loop:
<?php $first = true; ?>
<?php foreach ($prices as $item): ?>
<tr>
<td><input type="radio" name="price" value="<?= $item['price'];?>" class="price" <?= $first ? 'checked' : '' ?>> </td>
<td><input type="text" name="price" value=" <?= $item['price'];?>" class="price_field">€</td>
</tr>
<?php $first = false;?>
<?php endforeach; ?>
Whit this loop i get succesfull list of items and only first item is selected.
So now when page is loaded i want to get selected value and put him on other div like sum.
I try with jQuery but null
$(window).on("load", function(){
var price = $(".price");
var total = $(".total");
alert($(".price").val()); // null
});
The scenario:
I'm allowing a user to select a number of pizzas, they then go to a page where they can choose different options for each pizza. The idea is that as they change an option for a pizza the results are shown in a results div for that pizza with the price. If the user has chosen 3 pizzas there will be lots of options with three divs to show the results for each, and a grand total div.
I have successfully looped through and created the option boxes, but I am struggling to see the best way to get the selections of the dynamic form values so I can do calculations and run some ajax to populate the result divs.
This is the generated forms(though they could probably all go into one form)
<?php
$boxNum = 0; ///to append to form input id names
///start loop
foreach(loops through array){///start loop
$theid = ///this successfully assigns the id
$pizzaname = /// this successfully assigns the pizza name
?>
<div id="pizza_option_<?php echo $boxNum; ?>" >
<form action="" method="post">
<input name="theid_<?php echo $boxNum; ?>" id="theid_<?php echo $boxNum; ?>" type="text" value="<?php echo $theid; ?>" class="bk" >
<input name=" pizzaname _<?php echo $boxNum; ?>" id=" pizzaname _<?php echo $boxNum; ?>" type="text" value="<?php echo $pizzaname?>" class="bk">
<select name="sizes_<?php echo $boxNum; ?>" id="sizes_<?php echo $boxNum; ?>" class="bk">
<?php avaliable_sizes($id); ///fuction to get available sizes ?>
</select>
<select name="topping_<?php echo $boxNum; ?>" id="topping_<?php echo $boxNum; ?>" class="bk">
<?php avaliable_toppings($id); ///fuction to get available toppings ?>
</select>
</form>
</div>
<?php $boxNum ++; } // end of loop ?>
<div id="pizza_results_<?php echo $boxNum; ?>" >
Display selection choices and cost for pizza
</div>
<div id="grand_total_for_pizzas" >
Display total of all pizzas
</div>
I have found it difficult to find resources that, a cover both dynamic form input values and event trigger when a form input has been changed.
You will see from my pseudo code that I have appended a unique id to the input ID as this I am thinking this can be used to identify a set of pizza inputs.
If anyone can point me in the right direction I would be grateful. I only require guidance on identifying when there is a change on one of the values for a pizza, not on any calculations or anything else.
Ok, after a little more digging around I found a solution:
by adding an event to the inputs:
onchange="calc(this)"
I can append the id I assigned to the input ID and get the values of the other elements
function calc(elem) {
//just get the number
var id = $(elem).attr("id").match(/\d+$/);
//append the id to the element ID
alert($('#pizzaname_'+id).val());
}
You have to use event delegation for dynamically created elements.
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
Example:
$(document).ready(function(){
// to listen for value changes of the element with class 'bk':
// (event is attached to the document)
$(document).on('change', '.bk', function(){
var value = $(this).val();
// do stuff when value has been changed...
});
// attach event to other element (must be one of the parents of the inputs)
$('#some_parent_element').on('change', '.bk', function(){
var value = $(this).val();
// do stuff when value has been changed...
});
})
I would also add a data-id attribute to each input, so that you can easily get the id:
<select data-id="<?php echo $boxNum; ?>" name="sizes_<?php echo $boxNum; ?>" id="sizes_<?php echo $boxNum; ?>" class="bk">
And then in jQuery:
$(document).on('change', '.bk', function(){
var id = $(this).data('id');
var pizza_name = $('pizzaname_'+id).val();
});
I am creating a Data table with following code
<?php
foreach($redeemSales as $sale)
{
?>
<tr class='clickableRow<?php echo $isRead ? '' : ' newrow' ?>' href='#'>
<td><form><input type="checkbox" id="userSelection" name="userslection" ></form></td>
<td><?php echo $sale["ring"];?></td>
<td><?php echo formatFullDate($sale["soldDate"]) ?></td>
<td><?php echo $sale["saleType"]; ?></td>
<td>
<div class="col-lg-8">
<select name="type" id="redeemOptions" class="form-control">
<option value="None">None</option>
<option value="CD">(CD)</option>
<option value="Amex">American Express Card (Amex)</option>
</select>
</div>
</td>
</tr>
<?php }?>
I want to make it so if anyone change the option to any oe of CD Or Amex, it will set the selection to its row as checked.
jAVAScript code is here
<script language="javascript">
$(document).ready(function(e)
{
$('#redeemOptions').change(function(){
if($('#redeemOptions').val() == 'None')
{
document.getElementById("userSelection").checked = false;
}
else
{
document.getElementById("userSelection").checked = true;
}
});
});
</script>
As you can see that there is a for loop, so its rows getting added in a table. The above method works only for first row. If i change the options, it will set selection to Checked. But after first rows, no other row is showing that behavior. It is probably something to do with id of the elements.
How can one find out a solution so that other rows show same behavior. Secondly, if I have to get the ids or values of all rows that are "Checked" how will i do it in php
the problem is that an id has to identify one single element on the page, and you are generating multiple items with the same id. Change your select to something like the following:
<select name="type" class="form-control redeemOptions">
And then change your javascript function to the following, to take advantage of the fact that "this" will equal the object that the change event is being fired from:
$('.redeemOptions').change(function(){
var menuChanged = $(this),
parentForm = menuChanged.closest('form'),
correspondingCheckbox = parentForm.find('input[name=userSelection]');
if(menuChanged.val() == 'None')
{
correspondingCheckbox[0].checked = false;
}
else
{
correspondingCheckbox[0].checked = true;
}
});
Finally, remove the id="userSelection" from the checkbox and just leave the name. It won't hurt the functionality but it is technically invalid because again you can only have one element of a given id on the page.
As I can see for every $sale in $redeemSales you have a checkbox having id "userSelection" and a select box having id "redeemOptions". I advise you to use unique ids. So append $i=0...$i++ to the ids of both.
For Row 1: userSelection0 redeemOptions0
For Row 2: userSelection1 redeemOptions1
and so on..
In Select tag, use onchange event :-
<select name="type" id="redeemOptions<?php echo $i; ?>" class="form-control" onchange="foo(<?php echo $i; ?>)">
And write a javascript function :-
<script language="javascript" type="text/javascript">
function foo(id)
{
if($('#redeemOptions'+id).val() == 'None')
{
document.getElementById("userSelection"+id).checked = false;
}
else
{
document.getElementById("userSelection"+id).checked = true;
}
}
</script>
How can I append a select box with same option and different name.
I have a loop, where my php reads a sql table, and for each row, it creates a option tag
this is the function to append:
$(function(){
$('#add').click(function(){
var select = $('span[id=combo]').html();
$('#allCombo').append('<br/><span id="combo">'+select+'</span>');
});
});
this is the select box:
<span id="allCombo">
<span id="combo" name="combo">
<select name="item">
<?php foreach ($items as $item) { ?>
<option value="<?php echo $item->item_id; ?>">
<?php echo $item->item_name; ?></option>
<?php } ?>
</select>
</span>
</span>
Can anyone help me.
thanks before.
$(function(){
$('#add').click(function(){
var select = $('#combo').html();
$('<br/><span id="combo">'+select+'</span>').appendTo('#allCombo').find.('select').attr('name', 'uniqueName');
});
});
Use item[] as name . PHP will convert this to an array, so the selected values are in an array stored at $_POST['item'].
But more important is to not duplicate IDs. I suggest to remove the inner span completely, as
you cannot have duplicate IDs and
span tags have no name attribute
so there is no need to keep this tag.
<span id="allCombo">
<select name="item[]">
<?php foreach ($items as $item): ?>
<option value="<?php echo $item->item_id; ?>">
<?php echo $item->item_name; ?>
</option>
<?php endforeach; ?>
</select>
</span>
The JS code would be:
$(function(){
$('#add').click(function(){
$('#allCombo')
.append('<br />')
.append($('#allCombo select').first().clone());
});
});
var newSelect = $('select[name=item]').clone().attr('name', 'newselect');
$('#allCombo').append(newSelect);
You can always use the clone method:
var new_combo $('span#combo').clone();
new_combo.attr('name', 'second_combo');
new_combo.attr('id', 'second_combo'); // for valid html
$('#allCombo').append(new_combo);