Validate if more than one item was selected using jquery - javascript

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();
}

Related

save and read the checkbox value in the db, change the status of the label

I have to use a checkbox as a preference choice, so I save it in a mysql db to have it always available. When I select the chekbox the label changes to Enabled and vice versa. When you save (submit) the page sends an allert message indicating the status of the checkbox, and save the new value in the db 0 = disabled 1 = enabled and "reload" the same page and read the new values. Now I have the problem that the scripts intervene before I can read the value from the db. Only when I reload the page the second time do I get the correct values. I inserted a page refresh but I did not solve the problem.
-js-
<script>
function checked() {
if (document.getElementById("check1").checked){
$(check1).siblings('label').html('Abled');
alert("Abled Notify");
$.get("birthdaysend.php");
} else {
$(check1).siblings('label').html('Disabled');
alert("Disabled Notify");
}
}
// function change label checked
$('#check1').click(function() {
if ($(this).is(':checked')) {
$(this).siblings('label').html('Abled');
} else {
$(this).siblings('label').html('Disabled');
}
});
function urlCheck() {
if(window.location.href=="preference.php"){
//load page = read satus
checked();
}
}
urlCheck()
</script>
-Insert in to db-
$dbox = "SELECT value FROM box WHERE id = '1'";
$dbox= $db->ExecuteScalar($dbox);
print_r($dbox);//temp
if (isset($_POST['check1']) && $_POST['check1'] == '1') {
Execute("UPDATE box SET value='1' WHERE id = '1'");
header("Refresh:0");
}else{
Execute("UPDATE box SET value='0' WHERE id = '1'");
//header("Refresh:0");
}
-Html-
<form name="preference" action="preference.php" method="POST">
<div class="col-sm-4"><label class="container" for="check1">Tag 1</label><input type="checkbox" class="checkmark" name="check1" id="check1" value="1" <?php echo ($dbox == 1 ? 'checked' : '');?>></div>
<button style="float:left; margin-left: 0px;" type="submit" class="btn btn-primary"><i class="fa fa-floppy-o"></i> Save </button>
</form>
First of all change this, make update code first and then select
if (isset($_POST['check1']) && $_POST['check1'] == '1') {
Execute("UPDATE box SET value='1' WHERE id = '1'");
}else{
Execute("UPDATE box SET value='0' WHERE id = '1'");
}
$dbox = "SELECT value FROM box WHERE id = '1'";
$dbox= $db->ExecuteScalar($dbox);
print_r($dbox);//temp
Remove Urlcheck and checked functions from javascript
In label add this code instead of tag 1
echo ($dbox == 1 ? 'Abled' : 'Disabled');
A better way to do that would be with Ajax where the code to insert the value into a database is a different page from the one with a check box. Ajax is a JavaScript Library that has a synchronous ability.W3Schools tutorial for Ajax

Need to Toggle between All Sections and Sections With Only Input Value

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!

Show and hide element through different tabs PHP

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>

How to pass same class/id name php values from radio button to javascript?

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

Unable to check if a javascript checkbox array element is checked or not?

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;
}

Categories

Resources