I'm doing an online ordering system for our customers where when they log in, they're brought to a page where the items that they order are retrieved from a db, so it's dynamic and different for all customers.
Some customers have over 50 items, so as they're entering in quantities in the input fields, every now and then they'll want to see what they've ordered so far.
I'm trying javascript to toggle between complete order list and just to view what they've placed a quantity next to.
Retrieving the items via php, I put each array item in a SECTION then a DIV CLASS="w3-third..".
Below is the bottom portion of the php pull; the last LIST element is the quantity field and i put a SPAN around it in order to grab it for the count.
And below that is the javascript i'm attempting (I'm new to coding and first time asking a question here):
$i=1; //counter variable
while($rowtbl = mysqli_fetch_array($resulttbl)) {
?>
<section>
<div class="w3-third w3-margin-bottom" id="itemsToFilter" data-type="<?php echo $rowtbl['category']?>">
<ul class="w3-ul w3-border w3-center w3-hover-shadow" >
<li class="w3-padding-16"><?php echo htmlspecialchars($rowtbl['CustNo']) ?></li>
<li class="w3-green"><?php echo htmlspecialchars($rowtbl['description']) ?></li>
<li class="w3-padding-16"><?php echo htmlspecialchars($rowtbl['brand']) ?></li>
<li class="w3-padding-16"><?php echo htmlspecialchars($rowtbl['category']) ?></li>
<li class="w3-padding-16"><?php echo htmlspecialchars($rowtbl['itemNu']) ?>
<input type="hidden" name="prodid<?php echo $i; ?>" value="<?php echo $rowtbl['itemNu']; ?>" /></li>
<li class="w3-padding-16"><?php echo htmlspecialchars($rowtbl['pksz']) ?></li>
<li class="w3-padding-16"><?php echo htmlspecialchars($rowtbl['ea']) ?></li>
<?php if ($rowtbl['bc'] == "y" && $rowtbl['ea'] == 1) { ?>
<li class="w3-padding-16"><input type="checkbox" checked name="bc<?php echo $i; ?>" /></li>
<?php } elseif ( $rowtbl['bc'] == "y" && $rowtbl['ea'] == 0) { ?>
<li class="w3-padding-16"><input type="checkbox" name="bc<?php echo $i; ?>" /></li>
<?php }
else { ?>
<li class="w3-padding-16"><input type="hidden" name="bc<?php echo $i; ?>" /></li>
<?
}
?>
<input type="hidden" name="rows" id="rows" value="<?php echo $i; ?>" />
<li class="w3-padding-16"><span><input type="text" name="qty<?php echo $i; ?>" id="inputq" /></span></li>
</ul>
<div>
</section>
<?php $i++; //increment counter variable
} ?>
and the javascript, where nothing happens:
<script>
$(document).ready(function(){
$("button").click(function() {
var x = document.getElementsByTagName("span");
document.getElementById("demo").innerHTML = x.length;
var i;
for (var i = 0; i < x.length; i++) {
if(document.getElementById("inputq".[i]).value == ""){
$("span").parentsUntil("section").toggle();
}
}
});
});
</script
If i use just the javascript below and click the button, I do get the correct count, so it's reading the SPAN, I'm clearly doing something wrong with the for loop.
<script>
$(document).ready(function(){
$("button").click(function() {
var x = document.getElementsByTagName("span");
document.getElementById("demo").innerHTML = x.length;
});
});
</script>
I've also tried this below, but it toggles all 33 Sections initially, and if I put a quantity in a Section input field, it doesn't toggle, then if I put a quantity in a second Section, it toggles, etc.
$(document).ready(function(){
$("button").click(function(){
$('input[type=text]').each(function(){
if (this.value == "") {
$("span").parentsUntil("section").toggle();
};
});
});
});
I'm not sure if I need a combination of the two or something completely different. I've been looking online for days but all I can find are topics on toggling 1 element or 1 type of element.
Please help..
Thanks in advance.
#mfink ..and to anyone else viewing this...Ok I found something that helped me resolve my problem; i was also needing a live search option and found a script (http://www.designchemical.com/blog/index.php/jquery/live-text-search-function-using-jquery/) where i just had to change the selector to match mine and add 'allitems' class to my SECTION. Below is the live search script:
$(document).ready(function(){
$("#filter").keyup(function(){
// Retrieve the input field text and reset the count to zero
var filter = $(this).val(), count = 0;
// Loop through the Items list
$(".allitems div").each(function(){
// If the list item does not contain the text phrase fade it out
if ($(this).text().search(new RegExp(filter, "i")) < 0) {
$(this).fadeOut();
// Show the list item if the phrase matches and increase the count by 1
} else {
$(this).show();
count++;
}
});
// Update the count
var numberItems = count;
$("#filter-count").text("Number of Matches = "+count);
});
});
and below is how I changed it to resolve my posted question; I changed it so it loops through all input type 'text' and if it's blank, it toggles it:
$(document).ready(function(){
$("#getIt").click(function(){
// Retrieve the input field text and reset the count to zero
var filterI = $(this).val(), count = 0;
// Loop through the items list
$(":text").each(function(){
// If the list item does not contain a quantity fade it out
if ($(this).val() == "") {
$(this).parentsUntil("section").toggle();
// Show the list item if there is a quantity and increase the count by 1
} else {
$(this).show();
count++;
}
});
// Update the count
var numberItems = count;
$("#filterI-count").text("Items On Your Order = "+count);
});
});
I've tested it a few times, even submitting it to the db, and it has been working. If anyone sees a flaw/vulnerability, I'd sure love to know about it.
#mfink, thank you for looking into it for me!
Related
This code allows the user to select one or more models of cars graphically on a web page. I am in need to check if more than one was selected. How can I get this to count the number of selected items and if it's great than one alert("something")?? In short, I need to know if both Lexus and Inifiti were chosen in the example code here. I really need the count so if it's greater than 1 selected. Any help is great appreciated, not sure what I am doing wrong .
<div class="options-item-wrapper clearfix">
<?php
$modelOptions = array(
0 => array('title' => 'Lexus'),
1 => array('title' => 'Infiniti')
);
foreach ($modelOptions as $modelOption) {
$selected = '';
$optionValue = '';
if(in_array($modelOption['title'], $modelArray)) {
$selected = 'selected';
$optionValue = '<input class="vehicle-option"
type="hidden" name="model[]"
value="'.$modelOption['title'].'">';
}
echo '<div class="options-item '.$selected.'" data-vehicle="'.
$modelOption['title'].'">
<div>'.$modelOption['title'].'</div>
'.$optionValue.' </div>';
}
?>
</div>
I have tried this but no luck thus far :
var checkedNum = $('input[name="model[]"]:selected').length;
alert(checkedNum);
if (checkedNum > 1) {
alert('Validating the form2');
// User didn't check any checkboxes
} else {
die();
}
Your code doesn't work because hidden input elements don't have a selected state.
If I understand your code correctly, you add the class 'selected' to your options items if they're selected. Wouldn't you just need to count the number of options items with the selected class?
var checkedNum = $('.options-item.selected').length;
alert(checkedNum);
if (checkedNum > 1) {
alert('Validating the form2');
// User didn't check any checkboxes
} else {
die();
}
I have a select inside a form with different types of devices from the database (devices.insert.php):
Type:<select name="type" form="form_select" onchange="showDiv(this)">
<?php
$sql = "SELECT *
FROM Property
WHERE PRP_PRP_TYP_Id = 1";
$result = sqlsrv_query($con, $sql);
echo "<option disabled selected value> -- select an option -- </option>";
while ($row = sqlsrv_fetch_array($result)){
echo "<option value='".$row['PRP_Id']."'>".$row['PRP_Value']."</option>";
}
?>
</select><br>
<script type="text/javascript">
function showDiv(elem){
if(elem.value == 3 || elem.value == 24 || elem.value == 25){
document.getElementById('sc_div').style.display = "block";
}
else{
document.getElementById('sc_div').style.display = "none";
}
}
</script>
And when I select one of the items with the correct id, a div element turns visible with more options.
<div id="sc_div" style="display:none">
...
Register new SIM<br>
</div>
In sim_cards_insert.php I have a form with submit and cancel and when I press to go back (to devices_insert.php) the div sc_div is not visible again but the data that I've filled before is in the same place.
<button type="button" class="log-btn" onClick="history.go(-1)">Cancel</button>
How can I get it visible again passing through different windows?
Sounds like the browser is reverting the DOM to it's initial state - ie with the sc_div hidden.
Perhaps you could check the previous URL for the devices_insert.php page load.
<script type="text/javascript">
function showDiv(elem){
//example
var filename = document.referrer.split('/').pop();
if(filename === 'sim_card_insert.php'){
document.getElementById('sc_div').style.display = "block";
}
//...rest of function
</script>
Well, I have a form where the user can select an item with a checkbox, the user type how many items he wants to send with an input text, but there are some items that requires a serial number that a checkbox holds.
This is my approach:
<script>
function checkall()
{
var ok=true;
$('input:checkbox[id^="art"]:checked').each(function() {
var vals = $(this).val();
//first attempt
if (typeof document.getElementById(vals+"existencia") === 'undefined') {
ok=false;
return false;
alert("Error message");
}else
if (typeof document.getElementById(vals+"-serie")==='undefined') {
ok=false
return false;
alert("Error message 2");
}
//second attempt
if (obj.hasOwnProperty(vals+'existencia')) {
art = document.getElementById(vals+"existencia").value;
alert(art);
}else if (obj.hasOwnProperty(vals+'serial')) {
sert=document.getElementById(vals+"-serie").value;
alert(sert);
}
});
if(ok)
{
document.getElementById("myform").submit();
}
}
</script>
The script is intended to loop all checked checkboxes and if the input is empty stops and alerts the user and the other stage is when he checks an article with serial number, at least 1 have to checked and also alerts the client
The first attempt, I tried, got passed cause those elements are defined and second attempt throws obj is not defined, maybe I missunderstood the codes and answers I searched, can someone help to achieve my goal or explain me what I did wrong, thank you.
UPDATE:
if ($inicio == 0) {
echo "<tr bgcolor= '#f4f4f4' >";
$inicio = 1;
} else {
echo "<tr bgcolor= white>";
$inicio = 0;
}
?>
<td style="width: 10%;text-align: center;">
<input type="checkbox" name="art[]" id="art" value="<?php echo $articulo; ?>" /></td>
<td width="12%" align="center"><?php echo $diferencia_dias ?> días</td>
<td width="8%" style="text-align: center;"><?php echo $articulo; ?></td>
<td width="45%"><?php echo $descripcion; ?></td>
<?php
if($numserie>0){
$esto = trim($articulo);
$bus_serie = mssql_query("execute serial_madness '$esto','$almacen'");
echo "<td style='width:10%;text-align:left;'>";
while($res_serie = mssql_fetch_array($bus_serie))
{
echo '<input type="checkbox" id="'.$articulo.'-serie" name="'.$articulo.'-Serie[]" value="'.$res_serie["ARTICULO"].','.$res_serie["NUMSERIE"].'_'.$valor.' "> '.$res_serie["NUMSERIE"].' <br>';
}
echo "</td>";
}else{
?><td style="width:10%;text-align:center;"><input type="number" style="text-align:center;width:30px; height:30px;" id="<?php echo $articulo_c; ?>existencia" name="<?php echo
$articulo_c; ?>existencia" value="<?php echo (int)$existencias; ?>" min="1" max="<?php echo (int)$existencias; ?>"/></td>
<?php
} ?>
So, in order to check a checkbox you can just use jquery.
Example: $("#checkboxId").prop('checked', true);
The example above will check the checkbox with id "checkboxId", changing the true to false will uncheck the box;
If you want to check how many or which inputs are checked you can use the .length of the array returned by the jquery selector.
The following will check if all the checkboxes with ids starting with the word "test" are checked:
if($('[id^="test"]:checkbox').length == $('[id^="test"]:checkbox:checked').length)
{
// Do stuff here
}
Likewise you can check if nothing is checked if the length is equal to zero.
I prepared a simple example that I think tackles the general issue you are solving here.
https://plnkr.co/edit/2v6x1DXRpAiaKiBFSMz6?p=preview
Notice that when you click 'Submit' in my plunker example all checkboxes will automatically become checked.
If you click the 'Validate' button it will verify that all checkboxes are indeed checked.
You should be able to use my example to create a solution for your specific case.
You may also want to use the .is() jquery function
example:
$('#' + id).is(":checked")
See the following answer for some similar solutions and explanations: Check if checkbox is checked with jQuery
This is my problem. I am looping items from the database that contains items name and id. I have a radio button for each items. The id of that item is stored in the radio buttons value....Now what i want to achieve is when i click on the submit button,it will call a function call save() in javascript and save all the selected items ONLY .... i've been trying this for hours but i cant get it worked.
Here are my codes....
When i do my while looping from the DB, it will display the radio button and the items name...
<?php
$retrieveQuery = "SELECT * FROM `itemdb` WHERE `approve`= 1 AND `userId` = '$userId';";
$retrieveresult = mysqli_query($dbconnect, $retrieveQuery);
if(mysqli_num_rows($retrieveresult) > 0)
{
while($retrieverow = mysqli_fetch_assoc($retrieveresult))
{
?>
<p> </p>
<div style="background-color: rgba(0, 0, 0, 0.16);">
<input style="margin-bottom: -19px;" type="checkbox" class="item" name="item[]" value=<?php echo $retrieverow['itemID'] ?>>
<p style="margin-left: 26px;"><?php echo $retrieverow['itemName'] ?></p>
<p style="margin-top:-10px;margin-left:28px"><i><?php echo $retrieverow['category'] ?></i></p>
</div>
<?php
}
}
else
{
echo "Test : There is no approve Items to be displayed";
echo "Either wait for the admin to approve or upload items to start Trading ! ";
}
?>
This is my script:(How can i save my items?)
function save()
{
var f = document.getElementsByClassName('item').value; //my own items chosen frm invntry
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("confirmTrade").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("POST","trade.php?f="+f,true);
xmlhttp.send();
}
Right after i click the save() function it will send the data to another page using ajax method....
PS: Everything works fine...Other variables are passed successfully but only one item variable is being passed....
Thanks in advance!
Without looking into it too much, take a look at this line:
var f = document.getElementsByClassName('item').value;
document.getElementsByClassName gets an HTMLCollection of elements, so calling value on this doesn't make much sense. You'll need to loop through them and find the selected ones. I have it building an array then joining it into a comma separated list:
var checkboxes = document.getElementsByClassName('item');
var f = [];
for(var i = 0; i < checkboxes.length; i++){
if(checkboxes[i].checked == true)
f.push(checkboxes[i].value);
}
f = f.join();//makes comma seperated list
//proceed with ajax call
What is want is - when the checkbox is checked option no. 5 in select list will be selected and when the checkbox is unchecked option no. 0 will be selected in the select list.
The select list and the checkboxes are generated dynamically in the php code as below :
echo "<select name='coupons".$i."' id='coupons".$i."'>";
------- All Options --------
echo "</select>";
<input type='checkbox' name='myCheckbox[]' value='<?php echo $i."_".$row->id; ?>' onclick='setCCode("myCheckbox[]",<?php echo $i;?>)'>
-----------------------------------------------------------------------------
Solved the second requirement on my own now ..... thanks to all for your inputs
just added the following line in the checkAll() within the for loop
setCCode(children[i],i+1);
The javascript function :
function setCCode(checkbox_name,i)
{
var form_object = document.getElementsByName(checkbox_name+"["+i+"]");
var selname = document.getElementsByName("coupons"+i)[0];
if(form_object.checked) {
selname.selectedIndex = 5;
}
else {
selname.selectedIndex = 0;
}
}
The above issue is solved....... thanks to all
Now what i need to do is when a user checks a checkbox to select or deselect all the dynamically generated checkboxes on the form the above logic should work.
<input type='checkbox' name='checkall' onChange="checkAll(this, 'myCheckbox[]')">
<span class="chkall">Check / Uncheck All</span>
<input type='checkbox' name='myCheckbox[]' value='<?php echo $i."_".$row->id; ?>' onclick='setCCode(this,<?php echo $i;?>)'>
The javascript code i am using to select/deselect all checkboxes on form is as below :
function checkAll(parent, field)
{
var children = document.getElementsByName(field);
var newValue = parent.checked;
for (i = 0; i < children.length; i++){
if (children[i].disabled == false) {
children[i].checked = newValue;
}
}
}
function setCCode(Sender,i)
{
document.getElementsByName("coupons"+i)[0].selectedIndex = Sender.checked ? 5 : 0;
}
getElementsByName returns an array of objects. Replace the line with:
var form_object = document.getElementsByName(checkbox_name+"["+i+"]")[0];
You can pass refference to the checkbox itself as a parameter
<input type='checkbox' name='myCheckbox[]' value='<?php echo $i."_".$row->id; ?>' onclick='setCCode(this,<?php echo $i;?>)'>
function setCCode(Sender,i)
{
document.getElementsByName("coupons"+i)[0].selectedIndex = Sender.checked ? 5 : 0;
}
If you have a reference to the form that the checkbox is in, and it has a unique name in the form, then you can access it as:
form_object = form.elements[ checkbox_name + "[" + i + "]" ];
and you can also use the ternary operator to make the code more concise:
selname.selectedIndex = form_object.checked? 5 : 0;
Edit
Sorry, missed the obvious. If you pass a refereference to the checkbox in the handler, then you can also get the form (all form controls have a form property that references the form they are in). So as Jan Pfeifer suggested (abbreviated markup):
<input ... onclick='setCCode(this, <?php echo $i;?>)'>
then the script is just:
function setCCode(checkbox, i)
{
checkbox.form.elements['coupons' + i].selectedIndex = checkbox.checked? 5 : 0;
}