Set Attr Required when a checkbox for that field is checked - javascript

I have some looping rows which each row has a check box. And in each row there is a dropdown list which I want it to be set as required when the checkbox in the row is selected.
MARK NAME QUANTITY
---------------------------------------------------
[] inputForName1 Choose => 1,2,3,4,5
---------------------------------------------------
[] inputForName2 Choose => 1,2,3,4,5
---------------------------------------------------
[] inputForName3 Choose => 1,2,3,4,5
---------------------------------------------------
[] inputForName4 Choose => 1,2,3,4,5
---------------------------------------------------
[] inputForName5 Choose => 1,2,3,4,5
---------------------------------------------------
[SUBMIT]
(here [] is a Check-Box, and Choose => is a dropdown selection)
echo' <tr>
<td><input name="checkbox[]" type="checkbox" value="'.$i++.'" /></td>
<td><input name="items[]" type="text" value="'.$obj->items.'"></td>
echo' <td><select name="esquantity[]" required >
<option value="" >Choose Quantity</option>';
for ($q=1; $q <= $obj->quantity; $q++) {
echo' <option value="'.$q.'"> '.$q.' </option>'; }
echo' </select></td>';
echo'</tr>';
}
}
?>
<input type="submit" name="Submit" value="Submit">
</form>
</table>
<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
foreach($_POST['checkbox'] as $i) {
$product_name=$_POST['items'][$i];
$product_quan=$_POST['esquantity'][$i];
mysql_query("INSERT INTO estockClaims (items,
esquantity)
VALUES ('$product_name',
'$product_quan')");
}
}
?>
The problem is when I check only two checkboxes and I submit them, it asks me to select all the dropdown list in the quantity column.
Sketch of Jquery
<script type="text/javascript">
$(document).ready(function(){
$('input[type="checkbox"]').on('change', function(e)){
// var thisCheckbox = $(this);
var thisCheckbox = $('select[name="esquantity"]');
var thisRow = thisCheckbox.closest('tr');
if($(this.is(':checked')) {
}
.attr('required'));
}
}
</script>

I guess you didn't forget tags: <table><form> and close the input tags also <input ... />
So for your code you can try this (PHP/HTML part):
$i++;
echo' <tr>
<td><input name="checkbox['.$i.']" type="checkbox" value="'.$i.'" id="chb'.$i.'" onchange="enableList(this);" /></td>
<td><input name="items['.$i.']" type="text" value="'.$obj->items.'" /></td>';
echo' <td><select name="esquantity['.$i.']" id="select'.$i.'" disabled onchange="checkSelect(this)">
<option value="" >Choose Quantity</option>';
for ($q=1; $q <= $obj->quantity; $q++) {
echo' <option value="'.$q.'"> '.$q.' </option>'; }
echo' </select></td>';
echo'</tr>';
Then I've noticed in the SUBMIT part:
if($_SERVER["REQUEST_METHOD"] == "POST") {
foreach($_POST['checkbox'] as $key => $i) {
$product_name=$_POST['items'][$key];
$product_quan=$_POST['esquantity'][$key];
//more code
}
}
And the Javascript part:
function enableList(element) {
var select = document.getElementById("select"+element.id.substring(element.id.length-1));
if(element.checked === true){
select.disabled = false;
checkSelect(select);
}else{
select.disabled = true;
select.selectedIndex = 0;
}
}
function checkSelect(element){
if(!validate_select(element)){
element.setCustomValidity("Choose an option");
}else{
element.setCustomValidity("");
}
}
function validate_select(select){
if(select.selectedIndex === 0){
return false;
}else{
return true;
}
}
EDITED: In order to achieve the new purpose (submit only if at least one input is checked):
Add to the checkbox one class as an identifier: class="chb_group" (so you don't have to worry about other checkboxes)... and an id for the submit button maybe: id="btn_submit" and disabled by default
So you add:
function enableSubmit(){
if (document.querySelector('.chb_group:checked')) {
document.getElementById('btn_submit').disabled = false;
} else {
document.getElementById('btn_submit').disabled = true;
}
}
And call it in:
function enableList(element) {
var select = document.getElementById("select"+element.id.substring(element.id.length-1));
enableSubmit();
.....
}
NOTE: This code will work only in "modern" browsers because of some functions and properties like: setCustomValidity and querySelector

That is a javascript answer. Here's the Jquery answer: http://jsfiddle.net/n13wbran/5/
You can change the req attribute which I assigned myself on checkbox change event:
$("input[name^='checkbox']").change(function () {
var id = this.name.substring(8);
if (this.checked) {
$("[name='esquantity" + id + "']").attr("req", "true");
} else {
$("[name='esquantity" + id + "']").attr("req", "false");
}
});
Then on Submit click, check the lists with req == "true" and do the following:
$("input[name='Submit']").click(function () {
var i;
for(i = 1; i <= parseInt($("[name^='esquantity']").length); i++) {
if ($("[name='esquantity[" + i + "]']").attr("req") == "true" &&
$("[name='esquantity[" + i + "]']").val() == "")
alert("Please select a value for the required lists");
}
});

Related

Javascript checking if username already exists(duplicate)

I created a function that checks if the username already exists in the data list, but alert shows every time even if the username isn't in duplicate data list.
<form onsubmit="return validation()">
<table>
<tr>
<td>Username:</td>
<td><input type="text" id="user" name="user"></td>
<datalist id="list">
<option value="Tilen">
<option value="Marko">
<option value="Teja">
<option value="Tisa">
<option value="Rok">
<option value="Luka">
<option value="Mojca">
</datalist>
</tr>
</table>
</form>
<script>
function validation(){
var user = document.getElementById("user");
if(user.value.length <= 20 && user.value.length >= 3){
}
else{
alert("Username has to be between 3-20 characters.")
}
//duplication data list
var user = document.getElementById("user");
if(user.value == list.value){
}
else{
alert("Username already exists.")
}
}
</script>
You can get all the options using querySelector, iterate over them and compare then with user.value. Also you need list="polje_imen" in the input element.
function validacija() {
let user = document.getElementById('user');
let listOptions = document.querySelectorAll("#list option");
if (user.value.length <= 20 && user.value.length >= 3) {} else {
alert("Username has to be between 3-20 characters.")
}
for (let i = 0; i < listOptions.length; i++) {
if (listOptions[i].value === user.value) {
alert('The name already exist')
}
}
return false;
}
<form onsubmit="return validacija()">
<table>
<tr>
<td>Username:</td>
<td><input type="text" id="user" name="user" list="list"></td>
<datalist id="list">
<option value="Tilen">
<option value="Marko">
<option value="Teja">
<option value="Tisa">
<option value="Rok">
<option value="Luka">
<option value="Mojca">
</datalist>
</tr>
</table>
</form>
Edit: If you do not want to show the datalist, just use javascript.
function validacija() {
let user = document.getElementById('user');
let listNames = ["Tilen","Marko","Teja","Tisa","Rok","Luka","Mojca"];
if (user.value.length <= 20 && user.value.length >= 3) {} else {
alert("Username has to be between 3-20 characters.")
}
for (let i = 0; i < listNames.length; i++) {
if (listNames[i] === user.value) {
alert('The name already exist')
}
}
return false;
}
<form onsubmit="return validacija()">
<table>
<tr>
<td>Username:</td>
<td><input type="text" id="user" name="user"></td>
</tr>
</table>
</form>
Firstly, I don't think you're binding to the input on the datalist correctly. You can actually use the datalist as an autocomplete for the input if you simply change your input to look like this:
<input type="text" id="upor_ime" name="upor_ime" list="polje_imen">
If you have that in there, it becomes much more obvious if they choose a value that is not in the list or not from a visual perspective. Now when it comes to validating it in javascript, if you still want to take it that far, you're going to have to break out your list of possible names into an array so you can check to see if the string you're entering in the input exists in the array of strings. Because you're trying to compare an array of strings to a string, using the == operator in an if statement will not work. Here's a possible solution:
<form onsubmit="return validacija()">
<table>
<tr>
<td>Uporabniško ime:</td>
<td><input type="text" id="upor_ime" name="upor_ime" list="polje_imen"></td>
<datalist id="polje_imen"></datalist>
</tr>
</table>
</form>
<script>
var names = ["Tilen", "Marko", "Teja", "Tisa", "Rok", "Luka", "Mojca"];
var options = "";
for (let name of names) {
options += "<option value='" + name + "'>";
}
document.getElementById("polje_imen").innerHTML = options;
function validacija(){
var upor_ime = document.getElementById("upor_ime");
if(upor_ime.value.length > 20 || upor_ime.value.length < 3){
alert("Uporabniško ime mora imeti med 3-20 znakov.")
return;
}
//duplication data list
var polje_imen = document.getElementById("polje_imen");
if(names.includes(upor_ime.value)) {
alert("Uporabniško ime že obstaja.");
return;
} else{
// success
}
}
</script>
Here is a JSFiddle: http://jsfiddle.net/4f1hztr2/
Edit: I also changed around some of your if statement logic so that if the length of the item wasn't right it didn't continue executing the rest of the code.

jQuery Check and Uncheck all doesn't work

I have a list of checkboxes that I want to select and unselect.
The problem currently is that when I click All, all items in the list are added to an array called filter. However when I click All again, the list is repopulated with the items again. It is supposed to empty the filter array and uncheck all checkboxes.
How can I uncheck all the boxes if I select the All checkbox again?
The list consist of:
if(!empty($items)){ ?>
<input class="form-check-input select-item" data-item="All" type="checkbox" value="All" id="All">
<label class="form-check-label item-label" for="All">All </label>
<?php foreach ($items as $entry): ?>
<input class="form-check-input select-item" data-item="<?php echo $entry['short_name'];?>" type="checkbox" value="<?php echo $entry['short_name'];?>" id="<?php echo $entry['short_name'];?>">
<label class="form-check-label item-label" for="<?php echo $entry['short_name'];?>"><?php echo $entry['full_name'];?> </label>
<?php endforeach; ?>
<?php } ?>
This is the JavaScript I have at the moment:
$(".select-item").click(function(e){
var item = $(this).data('item');
if(item=="All") {
console.log($('#items input:checkbox').length);
if(filterAllChecked()) {
console.log("in");
$('#items input:checkbox').prop('checked',"");
filter = [];
} else {
$('#items input:checkbox').prop('checked', 'checked');
var items = $("#items input:checkbox:checked").map(function(){
return $(this).val();
}).get();
filter = items;
console.log($('#items input:checkbox').filter(":checked").length);
}
} else {
var index = $.inArray(item,filter);
if(this.checked && index === -1) {
filter.push(item);
} else {
filter.splice(index,1);
}
}
console.log(filter);
});
This is the check to see if all items have been selected:
function filterAllChecked(){
var checkboxes = $("#items input:checkbox");
return checkboxes.length === checkboxes.filter(":checked").length;
}
try this
$(".select-item").click(function(){
if($(this).attr('data-item') == 'All'){
if($(this).hasClass('select-item-checked')){
$(this).removeClass('select-item-checked');
$('.select-item').not('[data-item="All"]').prop('checked', false);
}else{
$('.select-item').not('[data-item="All"]').prop('checked', true);
$(this).addClass('select-item-checked');
}
}
var filter = $.makeArray($('.select-item:checked').not('[data-item="All"]').map(function(k,v){return $(v).val();}));
console.log(filter);
});
demo : https://jsfiddle.net/mo9khobg/5/
You should create a separate function getChecked() to get new values.
See Example:
function getChecked() {
var filter = [];
$('input:checkbox').not($('#All')).each(function(){
if ($(this).is(':checked')) {
filter.push($(this).val());
}
})
console.log(filter);
}
$('input:checkbox').not($('#All')).on('click', function(){
if (!$(this).is(':checked')) { $('#All').prop('checked', false); }
getChecked();
})
$('#All').on('click', function(){
($(this).is(':checked')) ? $('input:checkbox').not($(this)).prop('checked', true) : $('input:checkbox').not($(this)).prop('checked', false);
getChecked();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="form-check-input select-item" data-item="All" type="checkbox" value="All" id="All"> Check All <br>
<input type="checkbox" name="name1" value="name1"> Name 1
<input type="checkbox" name="name2" value="name2"> Name 2
<input type="checkbox" name="name3" value="name3"> Name 3
If you want have control of the array you can do it this way:
var inputArray = []
$('input').on('click', function(event){
console.log(event.target.checked)
modifyArray(event.target)
})
$('#selectAll').on('click', function(el){
$('.input').each(function(index, el){
console.log(el)
el.checked = !el.checked
modifyArray(el)
})
});
function modifyArray(el) {
console.log(el.checked)
if(el.checked){
if(inputArray.indexOf(el.name) === -1){
inputArray.push(el.name)
}
}else{
let index = inputArray.indexOf(el.name)
console.log(index)
inputArray.splice(index, 1)
}
console.log(inputArray)
}
Jsfiddle here:
https://jsfiddle.net/L2pacjp5/29/

AJAX jquery not responding and showing divs

I have code a simple form in which I retrieve data dynamically and then sending it to another page. Using that data i want some divs to be displayed on my page. It is returning divs when I check it simply without using AJAX. But now I have applied some AJAX and it is not working. Any suggestions please.
AJAX
$("document").ready(function() {
$("#search_keyword").on("submit", function (e) {
e.preventDefault();
$.post("keyword_search.php?query="+encodeURIComponent($("#keyword").val())+"category="+encodeURIComponent($("#category").val())+"store="+encodeURIComponent($("#store").val()), function (data) {
var res = JSON.parse(data);
if (res.divs) {
$('#search_result').html("");
for (var i = 0; i < res.divs.length; i++) {
$('#search_result').append(res.divs[i]);
}
} else {
$('#search_result').html("No matched coupons found !");
}
});
});
});
form
<form class="form-horizontal select-search" id="search_keyword" method="post">
<label class="control-label ">Keyword</label>
<input class="form-control" id="keyword" name="keyword" type="text">
<!-- Select Category -->
<label class="control-label " for="category">Select category</label>
<select class="category" id="category" name="category">
<?php
$sm=mysqli_query($con,"select * from categories ");
while ($row1 = mysqli_fetch_array($sm,MYSQLI_ASSOC)){
$cat_id = $row1['cat_id'];
$name = $row1['cat_name'];
echo '<option value="' . $cat_id . '">' . $name . '</option>';
}
?>
</select>
<label class="control-label " for="store">Select a store</label>
<select class="storesname" id="store" name="store">
<option selected="selected">Select Stores</option>
</select>
<button id="search_btn" name="search_btn" class="btn btn-danger">Search coupons</button>
</form>
<div id="search_result"> </div>
You need to change from button to submit type so that it can actually submit.
So change:-
<button id="search_btn" name="search_btn" class="btn btn-danger">Search coupons</button>
To:-
<input type="submit" id="search_btn" name="search_btn" class="btn btn-danger" value="Search coupons"/>
Note:- Make sure that jQuery library added before your script code so that it will work.
Change your code like below:-
$("document").ready(function() {
$("#search_keyword").on("submit", function (e) {
e.preventDefault();
var data = {'query':encodeURIComponent($("#keyword").val()),'category':encodeURIComponent($("#category").val()),'store':encodeURIComponent($("#store").val())};
$.post("keyword_search.php",data, function (data) {
var res = JSON.parse(data);
if (res.divs) {
$('#search_result').html("");
for (var i = 0; i < res.divs.length; i++) {
$('#search_result').append(res.divs[i]);
}
} else {
$('#search_result').html("No matched coupons found !");
}
});
});
});
And in your keyword_search.php check like this:-
<?php
echo "<pre/>";print_r($_POST); //check that how post data are coming
// rest do code accordingly
?>
Also remove method="post" from your current <form>
You just to change some thing in jQuery.
I have just changed "submit" to "click" and "#search_keyword" to "#search_btn"
$("document").ready(function() {
$("#search_btn").on("click", function (e) {
e.preventDefault();
$.post("keyword_search.php?query=" + encodeURIComponent($("#keyword").val())+encodeURIComponent($("#category").val())+encodeURIComponent($("#store").val()), function (data) {
var res = JSON.parse(data);
if (res.divs) {
$('#search_result').html("");
for (var i = 0; i < res.divs.length; i++) {
$('#search_result').append(res.divs[i]);
}
} else {
$('#search_result').html("No matched coupons found !");
}
});
});
});
It might help you

Two Radio buttons, a textarea and a number box, how to check if textarea is filled when radio1 is Yes and/or 2 is no

Here are the radios and textarea etc.
if(mysql_num_rows($canview) > 0) { ?>
<!-- Questions on return send all this to database then to place where dept. heads can see it-->
<div id = "returnform" >
<form action="" method="post">
<h4>Are any of the item(s) missing?</h4>
Yes<input type ="radio" name ="missing" id = "missing1" value = "Yes" required>
No<input type ="radio" name ="missing" id = "missing2" value = "No" >
<div class = "lossnum">
<input type="number" name="lossnum" id = "lossnum" placeholder="0">
</div>
<h4>Was every item put back/plugged in correctly?</h4>
Yes<input type ="radio" name ="putback" id = "putback1" value = "Yes" required>
No<input type ="radio" name ="putback" id = "putback2" value = "No">
<div class = "returncomments">
<h4>what happened?</h4>
<textarea name="comments"></textarea>
</div>
</div>
<input name="item_id" type="hidden" value="<?php echo $item->get_id(); ?>" />
<h4>Are you sure you want to return these <?php echo $item->get_name(); ?>? </h4>
<input type="submit" id="submit" name="submit" value="Return" />
right now all i have to change this is this:
$(document).ready(function () {
$(".lossnum").hide();
$(".comments").hide();
$(".returncomments").hide();
$(".commentup").hide();
$("#missing1").click(function () {
$(".lossnum").show();
$(".comments").show();
$(".returncomments").show();
});
$("#missing2").click(function () {
$(".lossnum").hide();
if($('#putback2').is(':checked')){
$(".comments").show();
$(".returncomments").show();
}
else{
$(".comments").hide();
$(".returncomments").hide();
}
});
$("#putback2").click(function () {
$(".comments").show();
$(".returncomments").show();
});
$("#putback1").click(function () {
if($('#missing2').is(':checked')){
$(".comments").hide();
$(".returncomments").hide();
}
else{
$(".comments").show();
$(".returncomments").show();
}
});});
this makes it so the textarea opens if 1 is yes and/or 2 is no, the only problem is if you then change the radios to no1/yes2 (which should be the only way the textarea does not show) it stays there, how would i make it so that it only shows up when something other than yes for 1 and/or no for 2 is true, and if that is changed it goes away and if it is not true does not show up.
Next I would like to make is so that when either 1 = Yes or/and 2 = no , the textarea is required to be filled out
you can for the most part ignore lost num
here is a JSfiddle for it
var itemMissing = false
, itemPluggedIn = true;
function updateCommentsDisplay(itemMissing, itemPluggedIn) {
if(itemMissing || !itemPluggedIn) {
$('#comments').show();
} else {
$('#comments').hide();
}
}
$('#nb-of-missing-items-field').hide();
updateCommentsDisplay(itemMissing, itemPluggedIn);
$('#missing input[name="missing-items"]').on('change', function () {
if(this.value === 'Yes') {
$('#nb-of-missing-items-field').show();
itemMissing = true;
} else {
$('#nb-of-missing-items-field').hide();
itemMissing = false;
}
updateCommentsDisplay(itemMissing, itemPluggedIn);
});
$('#plugged-in input[name="plugged-in-items"]').on('change', function () {
if(this.value === 'Yes') {
itemPluggedIn = true;
} else {
itemPluggedIn = false;
}
updateCommentsDisplay(itemMissing, itemPluggedIn);
});
http://jsfiddle.net/L7et15du/7/
Is that what you want to achieve?

Disable button with checkbox in table

I have an array of data on which each row has a checkbox which the user can check to select a row.
I want to make it so that if no row is selected, the "delete" button will be disabled.
The button gets disabled on page load, and the checkbox on row 1 works as planned, but if the table contains 2 or more rows the rest don't.
This is what I have so far:
<button class="btn btn-default modal-opener" id="chkboxdelbtn" onchange="toggle();" type="button" type="submit">Delete Selection</button>
<?php
$row = get_member_tskey_info($mysqli);
$i = 0;
foreach ($row as $r){
echo '<tr><td style="padding-right:0px;">';
if (($i<=2) && ($r['status'] == 1)){
echo '<input type="checkbox" name="keyselect[]" id="keyselect[]" value="' . $r['uid'] . '" /></td>';
}else{
echo '<input type="checkbox" disabled="disabled" value="" /></td>';
}
...
Javascript:
document.getElementById('chkboxdelbtn').disabled = true;
function toggle() {
if (document.getElementById('keyselect[]').checked == true) {
document.getElementById('chkboxdelbtn').disabled = false;
} else {
document.getElementById('chkboxdelbtn').disabled = true;
}
}
IDs have to be unique. Use a class instead.
foreach ($row as $r){
echo '<tr><td style="padding-right:0px;">';
if (($i<=2) && ($r['status'] == 1)){
echo '<input type="checkbox" name="keyselect[]" class="keyselect" value="' . $r['uid'] . '" /></td>';
}else{
echo '<input type="checkbox" disabled="disabled" value="" /></td>';
}
Javascript:
document.getElementsById('chkboxdelbtn').disabled = true;
function toggle(){
var keyselects = document.getElementsByClassName('keyselect');
for (var i = 0; i < keyselects.length; i++) {
if (keyselects[i].checked == true) {
document.getElementById('chkboxdelbtn').disabled = false;
break;
}
}
}
Be aware for the duplicate ID's on your checkbox. It cannot happen. Actually, you wouldn't even need an id to the checkbox, as you can make your toggle() function much simpler with querySelectorAll():
function toggle() {
document.getElementById('chkboxdelbtn').disabled =
( document.querySelectorAll("input[type='checkbox']:checked").length <= 0 );
}
This will look for all input checkboxes that are checked, and see if there's at least one. If not, it get's disabled.
https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll

Categories

Resources