How to build an SQL query from HTML checkboxes? - javascript

I need to create a query builder for SQL, where you can choose query constraints via HTML checkboxes. Each checkbox has a name,used for a column name (e.g ActorName), and a value for the column value (like Tom Hanks).
I'm having trouble deciding what is the best way to do this. I've tried adding/removing to a JavaScript object, and then iterating through each key-value pair, i.e each ActorName, each DirectorName, and append them to the WHERE constraint in SQL, but as the checkbox names are not unique, i.e there are many Actors, Genres etc, it complicates things. Right now, I'm using this method:
https://jsfiddle.net/Lompm0ew/5/
On checkbox checked, add the checkbox's name and value to a JS object, with the ActorName as the object key (as this will always be unique), and the checkbox name as the object value. I have a feeling this is bad practice, and I'm sure there is a better way to achieve my goal, but I'm out of ideas.
can anyone recommend a better method of building a query from checkboxes?

You can use "serialize" for get and send data with Ajax
First, add a form balsise in your HTML code
Example :
<form>
<div id="checkboxes">
<label>
<input type="checkbox" value="Tom Hanks" name="actorName[]">Tom Hanks</label>
<label>
<input type="checkbox" value="Tim Allen" name="actorName[]">Tim Allen</label>
<label>
<input type="checkbox" value="Don Rickles" name="actorName[]">Don Rickles</label>
<label>
<input type="checkbox" value="Jim Varney" name="actorName[]">Jim Varney</label>
<label>
<input type="checkbox" value="Wallace Shawn" name="actorName[]">Wallace Shawn</label>
<label>
<input type="checkbox" value="Fantasy" name="genreName[]">Fantasy</label>
<label>
<input type="checkbox" value="Comedy" name="genreName[]">Comedy</label>
<label>
<input type="checkbox" value="Children" name="genreName[]">Children</label>
<label>
<input type="checkbox" value="Animation" name="genreName[]">Animation</label>
<label>
<input type="checkbox" value="Adventure" name="genreName[]">Adventure</label>
<label>
<input type="checkbox" value="USA" name="countryName">USA</label>
</div>
</form>
Your javascript :
jQuery(document).ready(function($){
$(':checkbox').change(function() {
sendData();
});
})
function sendData () {
var $form = $('form');
$.ajax({
url : 'ajax.php',
data: $form.serialize(),
async : false,
success : function(response){
console.log(response);
}
});
}
Your ajax.php
<?php
var_dump($_REQUEST);
Show :
array(2) {
["actorName"]=>
array(3) {
[0]=>
string(9) "Tim Allen"
[1]=>
string(10) "Jim Varney"
[2]=>
string(13) "Wallace Shawn"
}
["genreName"]=>
array(1) {
[0]=>
string(9) "Animation"
}
}
Each time you click on checkbox, you send data for ajax.php. So, you can make the query server side
Edit : Sorry I've forgot : You can rename your checkbox name for send a array
<label>
<input type="checkbox" value="Tom Hanks" name="actorName[]">Tom Hanks</label>
<label>
<input type="checkbox" value="Tim Allen" name="actorName[]">Tim Allen</label>
<label>

Related

Laravel get the value of dynamic radio button in jquery created with for loop

I have a form in my view where I have populated some dynamic radio buttons using data from the database. Code looks like this-
<div class="row">
#foreach($status as $s)
<div class="col-md-6">
<label class="custom-control custom-radio">
<input id="status" name="status" value="{{$s->id}}" type="radio" class="custom-control-input">
<span class="custom-control-indicator"></span>
<span id="status-name" class="custom-control-description">
{{$s->specification}}
</span>
</label>
</div>
#endforeach
</div
and in HTML-
<div class="col-md-6">
<label class="custom-control custom-radio">
<input id="status" name="status" value="1" type="radio" class="custom-control-input">
<span class="custom-control-indicator"></span>
<span id="status-name" class="custom-control-description">Yes</span>
</label>
</div>
Yes
Yes
Now I want to send it to controller through ajax.I have tried this-
var status = document.getElementsByName('status').value;
if(status) {
$.ajax({
url: '/getpriceajax'+'/'+status,
type: "GET",
dataType: "json",
success:function(data) {
$('#calculated_price').val(data[0]);
document.getElementById("price-show").innerHTML = "Product price is "+ data[0]+"and "+data[1];
$(".phone-value-details").slideDown(700);
return false;
}
});
}else{
}
But it is always sending the value of the first radio button whether it is selected it or not. I have realized that it is happening because two radio buttons have the same name and by default, jquery is taking the first one. So, I think of renaming them dynamically. like-
name="status_{{$s->id}}"
But I don't know how to access this dynamic name or id in Jquery.
You don't need to change the name of the status input. But you need to change id attributes to make them unique on the whole document. Or just do not use them if they are not needed in client-side scripts or CSS.
To get the value of the status use the following code:
var status = $('input[name="status"]:checked').val();
you can use
$('input[name="status"]').each(function () {
if($(this).is(':checked')){
// $.ajax code with $(this).val()
}
});

jquery value from checkbox in loop not posting

I have a checkbox with the same name and id but different value.
I trying to get the value when I click on the checkbox in order to pass it to a ajax request. What ever I try I get the same result it only returns the first value in the list (it is actually in a php loop)
function checkCheckboxState() {
if ($('.displayme').is(':checked')) {
//tried all of these...
//var id = $('.displayme').first().attr( "value" );
//var id = $('.displayme').val();
//var id = $(this).val();
alert(id);
}
var id = $(":checkbox[name='displayme']:checked").val();
}
<input type="checkbox" name="displayme" value="27" id="displayme" class="displayme" onclick="checkCheckboxState()">
<input type="checkbox" name="displayme" value="28" id="displayme" class="displayme" onclick="checkCheckboxState()">
<input type="checkbox" name="displayme" value="29" id="displayme" class="displayme" onclick="checkCheckboxState()">
You shouldn't have the same id used several times on the same page.
You can bind an event on the change of the checkbox and then get the value with this :
$("checkbox.displayme").on("change",function(){
var checker = $(this).is(':checked');
//your ajax code here
});
And if your checkbox are generated on a php loop, you can use the index of the loop to generate different id (but with the code above you don't need any id).
Your first problem is that you have multiple elements with the same id. They need to be unique. In this case you could even remove them as you have the common class names to identify the elements.
To solve your actual problem you need to get a reference to the clicked checkbox within the event handler. As you're already using jQuery, you could do that using the change event handler. Try this:
$(function() {
$('.displayme').change(function() {
if (this.checked)
console.log(this.value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="displayme" value="27" class="displayme">
<input type="checkbox" name="displayme" value="28" class="displayme">
<input type="checkbox" name="displayme" value="29" class="displayme">
Alternatively you can use map() to build an array of all the selected checkboxes which can then be passed in a single AJAX request:
$(function() {
$('.displayme').change(function() {
var values = $('.displayme:checked').map(function() {
return this.value;
}).get()
console.log(values);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="displayme" value="27" class="displayme">
<input type="checkbox" name="displayme" value="28" class="displayme">
<input type="checkbox" name="displayme" value="29" class="displayme">

get multiple checkbox checked value in c#

In my web form I am generating multiple checkboxes dynamically. hence they are not in the control. I am trying to get the value using Request.Form[name] but it is not correct
<input type="checkbox" name="Suppresision" value="Suppresision" />Suppresision
Now I have a add button which dynamically (using Javascript) add more similar checkbox. So within my table element now I have
<input type="checkbox" name="Suppresision" value="Suppresision" />Suppresision
<input type="checkbox" name="Suppresision" value="Suppresision" />Suppresision
<input type="checkbox" name="Suppresision" value="Suppresision" />Suppresision
How do I try to get the values of all three ? I am doing the same for textbox but when I use Request.Form[textbox name] I get a comma separated values of all of them. But for the checkbox I do Request.Form["Suppresision"] I only get one value that too Suppresision instead of checked or not checked.How do I get all three value even if it not checked
If you absolutely need to get a list of all the checkbox controls you have dynamically added you could assemble them into a hidden input when you submit the form.
You need to include a hidden input for each set of checkboxes you add with a name like name="[checkbox name]_allValues"
<input type="checkbox" name="Suppresision" value="Suppresision1" />Suppresision 1
<input type="checkbox" name="Suppresision" value="Suppresision2" />Suppresision 2
<input type="checkbox" name="Suppresision" value="Suppresision3"/>Suppresision 3
<input type='hidden' value='' name="Suppresision_allVals">
Then add in this jQuery to loop the checkbox groups and you will have access to the full list of values for each checkbox on the server.
$(document.forms[0]).submit(function(event){
$('input[type=checkbox]').each(function( index ) { //loop all checkboxes
$itm = $( this );
$allVals = $('input[name=' + $itm.attr('name') + '_allVals]').first();
if ($allVals.length) { //see if we have a hidden input
$allVals.val($allVals.val()
+ ($allVals.val().length > 0 ? ',' : ' ') //add delemiter
+ ($itm.is(':checked') ? $itm.val() : '')); //add value
}
});
});
This way you will have access to the full list in Request.Form["Suppresision_allVals"] with blank values for unchecked boxes similar to what you have for empty textbox controls now.
You have same name attribute value for the three checkboxes. You should have different to make sure they can be read separately from the request form's collection on the server side. Also, in case of checkboxes, it should be checked attribute. Hopefully this will put you the right direction.
<input type="checkbox" name="Suppresision1" checked="checked" />
<input type="checkbox" name="Suppresision2" checked="" />
<input type="checkbox" name="Suppresision3" checked="" />
<input type="checkbox" class="chkItems" name="Suppresision1" checked="checked" />
<input type="checkbox" class="chkItems" name="Suppresision2" checked="" />
<input type="checkbox" class="chkItems" name="Suppresision3" checked="" />
var chkValue = [];
$('.chkItems:checked').each(function(i, e) {
chkValue.push({
chkItem : $(this).val()
});
});

Pass checkbox value IF the checkbox is checked

I have a list of checkboxes that looks like this:
<div class="checkbox">
<label><input type="checkbox" value="west" name="west" id="west" checked="{{isChecked}}">West</label>
</div>
<div class="checkbox">
<label><input type="checkbox" checked="{{isChecked}}" name="airport" id="airport" value="airport">Airport</label>
</div>
<div class="checkbox">
<label><input type="checkbox" checked="{{isChecked}}" name="north" id="north" value="north">North</label>
</div>
I have managed to pass the status of each checkbox as a boolean to the collection like this:
var eventLocation = [
event.target.west.checked,
event.target.airport.checked,
]
However, I would like to pass only the value of the checked checkboxes. I know I can pass the value of the checkboxes with event.target.west.value, but to get only the checked ones I would have to write many conditionals, which would not scale well. Is there a better way of doing this?
Thank you!
You can quickly gather all checked checkboxes with:
var checked = $("input:checked");
This will return an array that you can loop over to get the id, value, or name.
checked.forEach(function(c){
console.log('input id: '+c.id+' name: '+c.name+' value: '+c.val+' is checked!');
});

Need JQuery to mark checkboxes checked from list/array from database

Using SQL 2008 Server and the latest JQuery. If I query a column from the database and get the list/array how do I mark the checkboxes in each checkbox group 'checked'? Example checkbox groups and lists below:
list for category '1,7,20' (Jquery should mark checkboxes with values 1,7,10 checked)
list for likes '2,3' (Jquery should mark checkboxes with values 2 and 3 checked)
<form>
<input type="checkbox" class="category" name="category" value="14" />Blah
<input type="checkbox" class="category" name="category" value="1" />Blah1
<input type="checkbox" class="category" name="category" value="7" />Blah2
<input type="checkbox" class="category" name="category" value="20" />Blah3
<input type="checkbox" class="likes" name="likes" value="17" />Apple
<input type="checkbox" class="likes" name="likes" value="3" />Apple1
<input type="checkbox" class="likes" name="likes" value="2" />Apple2
<input type="checkbox" class="likes" name="likes" value="13" />Apple3
</form>
I tried the following JQuery code, but it doesn't work:
$.each(['1,7,20'], function (index, item) {
if ($('.category').val() === item) {
$(".category").prop("checked", true);
}
});
You're passing an array with a single element that is the string 1,7,20, not an array with three elements that are the strings 1,7 and 20, so I'm not sure why you're expecting it to work. If your input is in fact the string, you can split it on the comma to get an array with your numbers as strings:
var myString = '1,7,20';
var myArray = myString.split(',');
Then pass myArray to the $.each() function call.
There's also a problem with the code inside the function you've passed to $.each(). If you do call .val() on a jQuery object containing multiple elements, it will usually return the value for the first element only. You'll need to iterate again over the collection of elements, and use this to refer to the current element.
$.each(myArray, function(index, item){
$('.category').each(function(){
if(this.value === item) {
this.checked = true;
}
});
});
By the way, semantically, you should be using a filter. You can do the same thing while simultaneously increasing the readability of your code.

Categories