Setting checkbox values from database using jquery - javascript

I have a form in which i have two checkboxes (Checkbox 1 and Checkbox 2).
Now, what i want is:
1.) If only Checkbox 1 is selected while adding the details then in edit mode only Checkbox 1 should be selected. (which is happening)
2.) If only Checkbox 2 is selected while adding the details then in edit mode only Checkbox 2 should be selected. (which is happening)
3.) If both of them were selected while adding the details then in edit mode both Checkboxes should be selected. (which is not happening)
If someone can point me in the right direction or point my mistake that would be really great.
I have already checked many solutions for this here but none of them works for me or you can point me towards the link which i may have missed.
I will add my jquery function as well as how i am storing them in database in comma separated way.
Checkboxes:-
<div class = "error_placement_checkbox">
<div align = "center" class="ui inverted form" id = "idcheckbox">
<div align = "center" class=" inline required fields">
<label> Checkboxes </label>
<div class="field">
<div class="ui checkbox">
<input type = "checkbox" name = "p_act1" value = "Checkbox_1" >
<label> Checkbox 1 </label>
</div>
</div>
<div class="field">
<div class="ui checkbox">
<input type = "checkbox" name = "p_act2" value = "Checkbox_2" >
<label> Checkbox 2 </label>
</div>
</div>
</div>
</div>
</div>
My jquery function:-
<script type="text/javascript">
$(document).ready(function()
{
$('input[type="checkbox"]').each(function(index)
{
if ($(this).val() == "<c:out value = '${product.p_act}' />")
($(this).prop('checked' , true));
});
});
</script>
In my Controller Servlet:- // To store them in comma separated.
List<String> items = new ArrayList<>();
if (request.getParameter("p_act1") != null) { items.add (request.getParameter("p_act1")); }
if (request.getParameter("p_act2") != null) { items.add (request.getParameter("p_act2")); }
String p_act = String.join(" , ", items);
Edit:-
This is my whole jquery function
<script type="text/javascript">
$(document).ready(function()
{
$('input[type="checkbox"]').each(function(index)
{
// console.log(this.value);
if ("<c:out value = '${product.p_act}' />".split(",").includes($(this).val()))
($(this).prop('checked' , true));
// console.log(this.value);
});
});
</script>
edit2:-
<script type="text/javascript">
$(document).ready(function()
{
$('input[type="checkbox"]').each(function(index)
{
console.log(this.value);
if ("11,22".split(",").includes($(this).val()))
($(this).prop('checked' , true));
console.log(this.value);
});
});
</script>
in console:-
(index):269 Checkbox_1
(index):272 Checkbox_1
(index):269 Checkbox_2
(index):272 Checkbox_2

When debugging js/jquery, always use rendered code - you'll see that you have something like:
if ($(this).val() == "123,456")
At no point, does either of your checkboxes have the value of "123,456"
So the if never works if you have both ticked as it's comparing a single value with a combined string. You could compare by using split and checking with includes:
if ("123,456".split(",").includes($(this).val())
So your code would be:
if ("<c:out value = '${product.p_act}' />".split(",").includes($(this).val())
Or you could pass them to the js as an array instead of multiple join/split.

Related

Need to make html field ID dynamic for drop down options using jQuery

I am trying to make a search UI, where I am using Keys and Values for making an API call to backend.
These key value fields are dynamic - there is a button that adds extra field.
Now these, field depending on the key selected will have drop down on the value side...
I was able to create a logic for it but it is taking it for all the previous fields as well and not the current only.
I am seeing that the function works for the previous key value fields as well ( meaning when I add more filters - key value fields using a button, the last key value field whichever I will select on the key side will then the function will work for the above key value field as well, I ll add a photo for explanation)
I was looking for a solution to overcome this to keeping it to the latest key value fields only. ( I am thinking of using html id dynamic here for solution)
When I select Car or Phone the drop down should appear on the right,
add filter adds key value fields below..
I add multiple key value fields, the last key which I select will also make value side drop down to its above fields as well....
To change this I am thinking of using id = advanced-filter-2 as dynamic... I need solution for this as I am a beginner.
js fiddle link - https://jsfiddle.net/3wb8sq96/
function Getoptions(e) {
// $("#advancedFilter+1").change(function (e) {
var opt = e.value;
if (opt == "Color" || opt == "Phone") {
$("#advanced-filter-2").append("<option value='Green'></option>");
$("#advanced-filter-2").append("<option value='Yellow'></option>");
$("#advanced-filter-2").append("<option value='Red'></option>");
$("#advanced-filter-2").append("<option value='Orange'></option>");
} else {
$("#advanced-filter-2").empty();
}
// });
}
var filterCount = 1;
$(".removeFilter").toggle(filterCount > 1); //toggling appearance of removefilter button on condition
//Function to replicate fields in the form
function replicateFields(inputClass, anchorClass, i) {
// debugger;
var elementToReplicate = $(inputClass).first(), //Only clone first group of inputs
clonedElement = elementToReplicate.clone(); //Cloned the element
clonedElement.find("input").val(""); //Clear cloned elements value on each new addition
clonedElement.find("input").each(function() {
this.name = this.name;
});
clonedElement.insertBefore($(anchorClass));
}
//Calling function on click
$(".addFilter").click(function() {
replicateFields(".filterInputs", ".addFilter", filterCount++);
//console.log(filterCount);
$(".removeFilter").toggle(filterCount > 1);
});
// Function to remove added filter in the form
function removeFields(inputClass, anchorClass, i) {
// debugger;
var elementToRemove = $(inputClass).last(), //Only remove last group of inputs
removedElement = elementToRemove.remove(); //Removed the element
removedElement.remove($(anchorClass));
}
//Calling function on click
$(".removeFilter").click(function() {
removeFields(".filterInputs", ".removeFilter", filterCount--);
//console.log(filterCount);
$(".removeFilter").toggle(filterCount > 1); //toggling appearance of removefilter button on condition
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
<h2 class="card-title">Search</h2>
<form id="search" action="/service/table/search/" method="post">
<div class="form-group row">
<div class="filterInputs col-sm-12">
<input type="text" name="filterKey[]" id="advancedFilter" list="advanced-filter-1" onchange="Getoptions(this);" />
<datalist id="advanced-filter-1">
<option value="Color"></option>
<option value="Car"></option>
<option value="Phone"></option>
</datalist>
<input type="text" name="filterValue[]" list="advanced-filter-2" />
<datalist id="advanced-filter-2">
</datalist>
</div>
Add Filter
<a href="#!" style="text-align: center" class="removeFilter col-sm-2 col-form-label">Remove Filter</a
>
</div>
<div class="form-group row">
<div class="col-sm-10">
<button type="submit" class="btn btn-primary">Search</button>
</div>
</div>
</form>

How to display a textbox if "others" option from checkbox group is checked

I want to display a text box using JavaScript when the "Other" option is checked from a group of checkboxes. I'm using razor pages with asp.net core 2.2
I'm using the following script but it is not working.
function onSelectChange() {
var sel = document.getElementById('QuestionOptionId');
var strUser = sel.options[sel.selectedIndex].text;
if (strUser.startsWith('Other'))
document.getElementById('textBox').disabled = false;
else
document.getElementById('textBox').disabled = true;
}
</script>
Fruits.cshtml ( razor page view file)
#foreach (var option in Model.QuestionOptions)
{
<input type="checkbox" asp-for="QuestionOptionId" id ="QuestionOptionId" value ="#option.Value" onclick="onSelectChange()" /> #option.Text<br />
}
QuestionOptions is a selectList:
Value=1 Text= Apple,
Value=2 Text= Kiwi,
Value=3 Text =Other
whenever the user checks the checkbox for "Other", it should display a textbox.
What am I doing wrong here? I have read so many other answers but not able to figure out this one.
Update-1
I don't know why the post is not showing the textbox control...
I'm pasting it here again, it is outside the foreach loop. I have removed the angle brackets as I think it is mixing with formatting.
input type="text" id="textBox" name="response" disabled="disabled"
Full disclosure: I have never used Razor pages or asp.net
I'm having a hard time following how your javascript is detecting whether the other option is checked. It seems like your Fruits.cshtml is going to generate three separate inputs with the same "QuestionOptionId" id.
Also, your Fruits.cshtml snipped doesn't include the code for the textbox you'd like to enable, though I'm assuming you have a textbox with id "textBox" in the compiled HTML that you'd like to enable.
I would change your script out for this:
function onSelectChange(element) {
if (element === element.parentNode.querySelector(".other")) {
console.dir(element);
if (element.checked) {
document.getElementById("textBox").disabled = false;
} else {
document.getElementById("textBox").disabled = true;
}
}
}
You'll need to add the "other" class to your applicable "Other" input checkbox. You'll also need to change your Fruits.cshtml snippet so that the "onclick" function also passes the applicable element into the script.
#foreach (var option in Model.QuestionOptions)
{
<input type="checkbox" asp-for="QuestionOptionId" id ="QuestionOptionId" value ="#option.Value" onclick="onSelectChange(this)" /> #option.Text<br />
}
Here's a working example of the compiled code: https://codepen.io/bourn404/pen/yWVLdx
Try the following modification in the view and the javascript:
Add the label outside the input
#foreach (var option in Model.QuestionOptions)
{
<Lable>
<input type="checkbox" asp-for="QuestionOptionId" id="QuestionOptionId" value="#option.Value" /> #option.Text
</Lable>
<br />
}
<div>
<input type="text" id="textbox" disabled="disabled" />
</div>
Use $(this).parent().text().trim() to get the text
$('input:checkbox').on('click', function () {
if ($(this).parent().text().trim() === "Other") {
$('#textbox').removeAttr("disabled");
}
});
Update
If you want to hide the text box and hide the textbox when you uncheck the "other option , firstly you could change the disabled attribute to hidden ,and then determine if the text box contains hidden attribute in js like below :
<input type="text" id="textbox" hidden />
if ($(this).parent().text().trim() === "Other")
{
if ($('#textbox').is(':hidden')) {
$('#textbox').removeAttr("hidden");
}
else {
$('#textbox').attr("hidden", "hidden");
}
}

Dynamically Update DIV information based on CHECKBOX input value

I am trying to have a list of input checkboxes (which will be generated by PHP at a later time) but for now the content is static. So based off of the input, be able to select an employee, populates my div based on the selection and when unchecking the input, remove that same employee. I also need to be able to select multiple employees, instead of just one. Currently it updates the div with an employee but I cannot remove said employee. I can also only select one employee at a time (need to be able to click as many employees as needed all at once).
Here is what I got:
HTML
<div id="employee-list">
</div>
<div class="small-2 columns bord-right3 check-box">
<input type="checkbox" class="boxid" value="Joe Smith" name="employees">
<label class="checkbox-select">Select</label>
</div>
<div class="small-10 columns bord-right3">
<span class="employee-name">Joe Smith</span>
</div>
<div class="small-2 columns bord-right3 check-box">
<input type="checkbox" class="boxid" value="John Smith" name="employees">
<label class="checkbox-select">Select</label>
</div>
<div class="small-10 columns bord-right3">
<span class="employee-name">John Smith</span>
</div>
JS
$('input[name="employees"]').change(function () {
var inputVal = $('input[name="employees"]:checked').map(function () {
return this.value;
}).get();
console.log(inputVal);
if ($(this).prop('checked')) { //which checkbox was checked
if ($(this).val() == inputVal ) {
$("#employee-list").append('<span class="employee-name2_1">X ' + inputVal + '</span>');
}
} else {
$('.li_'+$(this).val()).remove();
console.log('item removed');
}
});
Any help is greatly appreciated! Please let me know if I have missed anything.
If I understand the goal correctly some of your code inside the change listener was unnecessary. You don't have to use map to get the value of the checkbox, $(this).val() is sufficient. From there a single if/else can add or remove the information as necessary.
Fiddle
$('input[name="employees"]').change(function () {
var inputVal = $(this).val();
var className = inputVal.replace(/ /g, '_');
if ($(this).prop('checked')) { //which checkbox was checked
$("#employee-list").append('<span class="span_' + className + '">X ' + inputVal + '</span>');
} else {
$('.span_'+className).remove();
console.log('item removed');
}
});

Show/Hide JQuery?

I have a problem where I have to show/hide multiple labels inside of the same td tag. Here is my JQuery code:
$j( document ).ready(function() {
var records = [];
var userID = 'here I am passing user ID'
~[tlist_sql;
SELECT ID1, User_ID, ID2
From RESERVATIONS
]
records.push({'idOne':"~(ID1)",'idTwo':"~(User_ID)",'idThree':"~(ID2)"});
[/tlist_sql]
for(var i=0; i< records.length; i++){
//here I am looking for matchin userID in my records array
if(records[i].idTwo == userID){
//If match, I want to hide input field and display name.
$j('#hide_' + records[i].idOne).parent('.hideEmail').hide().next('.showName').show();
}
//Here I'm looking if any of my records idThree has value 0
if(records[i].idThree == '0'){
//if match hide input and show word 'Reserved'
$j('#hide_' + records[i].idOne).parent('.hideEmail').hide().next('.showResreved').show();
}
}
});
Here is my html code:
<td>
<span class="hideEmail">
<input type="text" value="" id="hide_~(ID1)"/>
</span>
<label class="showName" style="display:none">
<span class="firstLast">Display Name</span>
</label>
<label class="showReserved" style="display:none">
<span class="notavailable">Reserved</span>
</label>
</td>
So problem show up once I combined both labels. At the first point I had only label with the class 'showName' and my logic worked fine. But once I added one more if statement in my JQuery and added another label with class 'showReserved' my code still displayed name label and class 'hideEmail' was hidden but class 'showReserved' never was displayed. Can anyone tell me why this does not work? Should I not combine two labels or something is wrong in my jquery?
Here is my working example: https://jsfiddle.net/dmilos89/nephebbv/2/
The problem its in this part:
$j('#hide_' + records[i].idOne).parent('.hideEmail').hide().next('.showResreved').show();
You typed "showReserved" wrong.
Here's a simple fix:
$j('#hide_' + records[i].idOne).parent('.hideEmail').hide().next('.showReserved').show();

Javascript Checkboxes Scenario

I currently have a code that shows a DIV based on two checkboxes. Currently, you can select both checkboxes and both DIVs will show. I do not want this to occur. How can I make it so you select both checkboxes it shows another DIV?
In summary, one checkbox shows one DIV, another checkbox shows another, both will show something completely else.
<input type="checkbox" name="checkbox_insert"
id="checkbox_insert" value="insert">Insert<br>
<input type="checkbox" name="checkbox_update"
id="checkbox_update" value="update">Update</p>
<script type="text/javascript">
$('#checkbox_insert').change(function() {
$('#insert_div').toggle();
});
$('#checkbox_update').change(function() {
$('#update_div').toggle();
});
</script>
<div id="insert_div" style="display:none">
INSERT
</div>
<div id="update_div" style="display:none">
UPDATE
</div>
<div id="both_div" style="display:none">
BOTH
</div>
var $i = $('#checkbox_insert, #checkbox_update'),
$d = $('div'),
$b = $d.filter('#both_div');
$i.change(function () {
$b.toggle($i.filter(':checked').length === $i.length);
$d.filter('#' + this.value + '_div').toggle(this.checked);
});
http://jsfiddle.net/EeJXy/
You'll want something like this (using jQuery):
EDIT Updated booleans in toggle() (working example here http://jsfiddle.net/uYUK2/):
$('input[type="checkbox"]').on('change', function() {
var inserted = $('#checkbox_insert').prop('checked');
var updated = $('#checkbox_update').prop('checked');
$('#both_div').toggle(inserted && updated);
$('#insert_div').toggle(inserted && !updated);
$('#update_div').toggle(updated && !inserted);
});

Categories