enable or disable checkbox from javascript not happening - javascript

<legend>Information</legend>
<div class="row">
<div class="col-xs-12 col-sm-3 col-md-3">
<label><strong>{{$val}}</strong></label>
</div>
<script>
var str = "Hello world!";
var res = str.substring(0, 2);
if (res == ee) {
alert("Hello! I am an alert box!");
} else if (res == he) {
document.getElementById("checkbox").checked = true;
}
</script>
<div class="col-xs-12 col-sm-3 col-md-3">
<input type="checkbox" name="operator" id="checkbox" >
</div>
<div class="col-xs-12 col-sm-3 col-md-3">
<input type="checkbox" name="operator" id="checkbox">
</div>
<div class="col-xs-12 col-sm-3 col-md-3">
<input type="checkbox" name="operator" id="checkbox">
</div>
</div>
<br/>
i have included my html piece of code above. i don't know why check box is not responding for this piece of JavaScript.
note: i should use JavaScript in the position between div's

value ee and he should be wrapped in quotes. also note that IDs should be unique, you can rather use common class and use getElementsByClassName to target all of them using class :
var res = str.substring(0, 2);
if(res=='ee'){
alert("Hello! I am an alert box!");
}
else if(res=='he'){
document.getElementsByClassName("checkbox").checked = true;
}

Condition is wrong. If you want check the string element you have to use "" or ''. Otherwise it will treat as a variable.
if(res=="ee"){
alert("Hello! I am an alert box!");
}
else if(res=="he"){
document.getElementById("checkbox").checked = true;
}

Related

How can I show div if keyword match

If searched keyword matches I am able to show the matched input text and its related div with category name. Now what I am trying is to search over category names as well.
If searched keyword matches with the category name this div should visible. also if searched keyword matches with the input names this is also visible with its category name.
$('.bar-input').on('keyup', function() {
var search_input = $(this).val().toLowerCase();
var tags = $('.wrap label');
var count = tags.length;
var text_input = $(this).val().length;
var category = $('.category-type');
// // searching for tags
for (i = 0; i < count; i++) {
if (!search_input || tags[i].textContent.toLowerCase().indexOf(search_input) > -1) {
tags[i].parentNode.style['display'] = 'block';
} else {
tags[i].parentNode.style['display'] = 'none';
}
}
// If no tags found category will be hidden
$(".category").not(".stcw-screen").map(function() {
let flag = true;
$(this).find('.wrap').map(function() {
if ($(this).css("display") != "none") {
flag = false;
}
});
if (flag) {
$(this).css("display", "none");
} else {
$(this).css("display", "block");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="bar-input" type="text" placeholder="search">
<div class="category">
<div class="category-name">
<h5>Country</h5>
</div>
<div class="options">
<div class="wrap">
<label><input type="checkbox">America</label>
</div><div class="wrap">
<label><input type="checkbox">France</label>
</div>
</div>
</div>
<div class="category">
<div class="category-type">
<h5>Sports</h5>
</div>
<div class="options">
<div class="wrap">
<label><input type="checkbox">Football</label>
</div><div class="wrap">
<label><input type="checkbox">Cricket</label>
</div>
</div>
</div>
<div class="category">
<div class="category-type">
<h5>Operating system </h5>
</div>
<div class="options">
<div class="wrap">
<label><input type="checkbox">linux</label>
</div><div class="wrap">
<label><input type="checkbox">windows</label>
</div>
</div>
</div>
To do what you require you can loop through each category and first determine if the .category-type matches the search term using a case-insensitive implementation of :contains and then display that section with all options visible, or if not you can look at each option in turn using the same :icontains() selector and show them individually.
The logic would look something like this:
// case-insensitive :contains implementation (credit: https://stackoverflow.com/a/8747204/519413)
jQuery.expr[':'].icontains = (a, i, m) => $(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
var $categories = $('.category');
var $types = $('.category-type');
$('.bar-input').on('input', function() {
var search_input = $(this).val().toLowerCase().trim();
if (search_input.length == 0) {
// no search term entered, reset state to show all items
$('.wrap label').add($types).show()
return;
}
$categories.each((i, category) => {
let $cat = $(category);
let $type = $cat.find('.category-type').hide();
let $labels = $cat.find('.wrap label').hide();
if ($type.is(`:icontains("${search_input}")`)) {
// match on category type, show category-type and all child options
$type.add($labels).show();
} else {
// no match on category, show only if match on child option
let $matches = $labels.filter(`:icontains("${search_input}")`).show();
$type.toggle($matches.length > 0);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="bar-input" type="text" placeholder="search">
<div class="category">
<div class="category-type">
<h5>Country</h5>
</div>
<div class="options">
<div class="wrap">
<label><input type="checkbox">America</label>
</div>
<div class="wrap">
<label><input type="checkbox">France</label>
</div>
</div>
</div>
<div class="category">
<div class="category-type">
<h5>Sports</h5>
</div>
<div class="options">
<div class="wrap">
<label><input type="checkbox">Football</label>
</div>
<div class="wrap">
<label><input type="checkbox">Cricket</label>
</div>
</div>
</div>
<div class="category">
<div class="category-type">
<h5>Operating system </h5>
</div>
<div class="options">
<div class="wrap">
<label><input type="checkbox">linux</label>
</div>
<div class="wrap">
<label><input type="checkbox">windows</label>
</div>
</div>
</div>

Set checkbox Disable when another is checked

how can I add the class "disabled" to the second checkbox if the first one is selected and vice versa.
I don't know where I'm wrong, this is my code, in which I imagined two functions to include where I will turn off the secondary checkbox in each. (maybe it can in one function for sure, but I don't know), this is my example, if someone can correct me where I went wrong, thank you.
function disableNewmobileOption(ev) {
ev.preventDefault();
var inputElementLabel = $(ev.currentTarget);
var inputElement = inputElementLabel.siblings("input");
if (inputElement.is(':checked')) {
if (inputElement.attr("id") === "b_mobnr") {
$(".newmobile .circle-buttons").addClass("disabled");
} else {
$(".b_mobnr .circle-buttons").removeClass("disabled");
}
}
}
function disableBMobOption(ev) {
ev.preventDefault();
var inputElementLabel = $(ev.currentTarget);
var inputElement = inputElementLabel.siblings("input");
if (inputElement.attr("id") === "newmobile") {
$(".b_mobnr .circle-buttons").addClass("disabled");
} else {
$(".newmobile .circle-buttons").removeClass("disabled");
}
}
<div class="row">
<div class="col-sm-4 newmobile">
<h4>Optionen</h4>
<span class="circle-buttons">
<input type="checkbox" name="b_mobnr" id="b_mobnr" value="0">
<label for="b_mobnr" onclick="disableNewmobileOption(event)">Mobile Option</label>
<div class="check square-check"></div>
</span>
</div>
<div class="col-sm-12 b_mobnr">
<span class="circle-buttons">
<input type="checkbox" name="newmobile" id="newmobile" value="0">
<label for="newmobile" onclick="disableBMobOption(event)">Newmobile Option </label>
<div class="check square-check"></div>
</span>
</div>
</div>
You can use .not() to add disabled class to other span tag when your checkbox is checked.Other way would be passing this inside your function call then depending on if the checkbox is checked add class to other span.
Demo Code :
/*$(".circle-buttons input[type=checkbox]").on("change", function() {
$(".circle-buttons").removeClass("disabled") //remove from all
if ($(this).is(":checked")) {
$(".circle-buttons").not($(this).closest(".circle-buttons")).addClass("disabled") //other span tag
}
})*/
function disableNewmobileOption(el) {
var inputElement = $(el);
//remove class from all
$(".circle-buttons").removeClass("disabled");
//check if checkbox is checked
if (inputElement.is(':checked')) {
//add class to other
$(".b_mobnr .circle-buttons").addClass("disabled");
}
}
function disableBMobOption(el) {
var inputElement = $(el);
$(".circle-buttons").removeClass("disabled");
if (inputElement.is(':checked')) {
$(".newmobile .circle-buttons").addClass("disabled");
}
}
.disabled {
color: grey;
pointer-events: none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="col-sm-4 newmobile">
<h4>Optionen</h4>
<span class="circle-buttons">
<!--aded click event on checkbox-->
<input type="checkbox" name="b_mobnr" id="b_mobnr" onclick="disableNewmobileOption(this)" value="0">
<label for="b_mobnr" >Mobile Option</label>
<div class="check square-check"></div>
</span>
</div>
<div class="col-sm-12 b_mobnr">
<span class="circle-buttons">
<input type="checkbox" name="newmobile" id="newmobile" onclick="disableBMobOption(this)" value="0">
<label for="newmobile">Newmobile Option </label>
<div class="check square-check"></div>
</span>
</div>
</div>

Checkbox filter products with jquery and keep state with reload

I want to create a page where I can filter products with checkboxes but also to keep the filter choices on page reload.
<div class="checkbox checkbox-success checkbox-inline ">
<input type="checkbox" id="1" value="option1" >
<label for="1">Adidas</label>
</div>
<div class="checkbox checkbox-success checkbox-inline ">
<input type="checkbox" id="2" value="option2" >
<label for="1">Nike</label>
</div>
<script>
var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {},
$checkboxes = $("#checkbox-container :checkbox");
$checkboxes.on("change", function(){
$checkboxes.each(function(){
checkboxValues[this.id] = this.checked;
});
localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
});
// On page load
$.each(checkboxValues, function(key, value) {
$("#" + key).prop('checked', value);
});
$('input[type="checkbox"]').change(function() {
if ($('input[type="checkbox"]:checked').length > 0) {
$('.products >div').hide();
$('input[type="checkbox"]:checked').each(function() {
$('.products >div[data-category=' + this.id + ']').show();
});
} else {
$('.products >div').show();
}
});
</script>
I have found both jquery scripts and they both work fine by themselves. By this I mean that I can get to filter the products when checking/unchecking the checkboxes. When checking a checkbox and reloading the page, the checkbox is correctly checked but products has not been filtered. So I need to merge the 2 scripts so that products also will be filtered when reloading the page with a checked checkbox.
Hope someone can guide me a bit here.
--- UPDATE ---
I have created an example here: maxie.dk/filter.php
1) Tick a checkbox
2) Product filter is activated and only products with matching value is displayed
3) Refresh page
4) Checkbox checked is kept as it should but all products are now again visible. Only matching products to the ticked checkbox should be visible.
Thanks
If I get your issue right - you want to move your "business logic" that happens on each input change to a separate function so that it can be executed also upon page reload.
...
// On page load
$.each(checkboxValues, function(key, value) {
$("#" + key).prop('checked', value);
});
// your business logic
function updateProducts() {
if ($('input[type="checkbox"]:checked').length > 0) {
$('.products >div').hide();
$('input[type="checkbox"]:checked').each(function() {
$('.products >div[data-category=' + this.id + ']').show();
});
} else {
$('.products >div').show();
}
}
$('input[type="checkbox"]').change(function() {
// execute for each change
updateProducts();
});
// execute on page load
updateProducts()
I have re-write this such that it will update the localstorage and also check and show product that is save in localstorage. It will also remove or show product on checked. Check it out.
<div class="col-xs-12 col-sm-12">
<div class="breadcrumb" id="checkbox-container">
<h4 class="visible-xs"></h4>
<span class="hidden-xs"></span>
<div class="checkbox checkbox-success checkbox-inline ">
<input type="checkbox" id="1" value="1" />
<label for="1">Adidas</label>
</div>
<div class="checkbox checkbox-success checkbox-inline ">
<input type="checkbox" id="2" value="2" />
<label for="2">Reebok</label>
</div>
<div class="checkbox checkbox-success checkbox-inline ">
<input type="checkbox" id="3" value="3" /> <label for="3">Nike</label>
</div>
ยด
</div>
</div>
<div class="products">
<div
class="col-xs-6 col-ms-4 col-sm-4 col-md-4 col-lg-3 padding-btm "
data-category="1" >
PRODUCT 1
</div>
</div>
<div class="products">
<div
class="col-xs-6 col-ms-4 col-sm-4 col-md-4 col-lg-3 padding-btm "
data-category="1">
PRODUCT 2
</div>
</div>
<div class="products">
<div
class="col-xs-6 col-ms-4 col-sm-4 col-md-4 col-lg-3 padding-btm "
data-category="2"
>
PRODUCT 3
</div>
</div>
<div class="products">
<div
class="col-xs-6 col-ms-4 col-sm-4 col-md-4 col-lg-3 padding-btm "
data-category="3"
>
PRODUCT 4
</div>
</div>
var checkedValues =JSON.parse(localStorage.getItem('checkboxValues')) || [],
$checkboxes = $("#checkbox-container input[type=checkbox]");
function loadPrevious(){
if(checkedValues.length>0){
$("div.products > div").hide();
$.each(checkedValues,function(i,v){
$("#checkbox-container input[type=checkbox]#" + v ).prop('checked',true);
$('.products >div[data-category=' + v + ']').show();
})
}
}
loadPrevious();
$checkboxes.change(function(e) {
e.preventDefault();
if($(this).prop("checked") == true){
checkedValues.push($(this).attr("id"));
loadPrevious();
localStorage.setItem("checkboxValues", JSON.stringify(checkedValues));
}else{
var checkId = $(this).attr("id"),
arr = JSON.parse(localStorage.getItem('checkboxValues'));
$('.products >div[data-category=' + checkId + ']').hide();
var newArr = $(arr).not([checkId]).get();
localStorage.setItem("checkboxValues", JSON.stringify(newArr));
}
});
See the demo here

How to delete dynamic field using jquery

I am building script where I can add some dynamic fields and then delete it if I want. But I can't delete that first el class in my script, because it deletes all within input_fields_container class. How to do it correctly? Here's my code:
<div class="input_fields_container">
<div class="col-lg-12">
<div class="col-lg-2"></div>
<button class="btn btn-sm btn-primary add_more_button" style="float: left; margin-bottom: 10px;">
#lang('main.add more fields')
</button>
</div>
#foreach(Auth::user()->test as $data)
<div class="el">
<div class="form-group">
<label class="col-lg-2 control-label">#lang('main.test')</label>
<div class="col-lg-6">
<input type="text" name="test[]" class="form-control" value="{{ $data->test }}" >
</div>
</div>
</div>
#endforeach
</div>
<script type="text/javascript">
$(document).ready(function() {
var max_fields_limit = 10; //set limit for maximum input fields
var x = 1; //initialize counter for text box
$('.add_more_button').click(function(e){ //click event on add more fields button having class add_more_button
e.preventDefault();
if(x < max_fields_limit){ //check conditions
x++; //counter increment
$('.input_fields_container').append('<div class="el"><div class="form-group"><label class="col-lg-2 control-label">#lang('main.test')</label><div class="col-lg-6"><input type="text" name="test[]" class="form-control"></div></div><div class="form-group"><label class="col-lg-2 control-label"></div></div><div>#lang('main.delete')</div></div>');
}
});
$('.input_fields_container').on("click",".remove_field", function(e){ //user click on remove text links
e.preventDefault(); $(this).parents().eq(1).remove(); x--;
})
});
</script>
Your HTML in your append is structured wrong. Your div for the remove_field is not inside the '.el' div.
Try this...
$('.input_fields_container').append('<div class="el"><div class="form-group"><label class="col-lg-2 control-label">Main.test</label><div class="col-lg-6"><input type="text" name="test[]" class="form-control"></div></div><div class="form-group"><label class="col-lg-2 control-label"></div><div>main.delete</div></div></div>');
https://jsfiddle.net/chadsaun/Ljxw03Lp/
Try this
You need to change the class="el" to id="el"
$(document).on('click', '.remove_field', function () {
$('#el').closest('#el').remove();
});
You can give that 'a' tag an onclick function by id in the for loop. and one id for div with class name 'el' something like this code below:
$('.add_more_button').click(function(e){ //click event on add more fields button having class add_more_button
e.preventDefault();
if(x < max_fields_limit){ //check conditions
x++; //counter increment
$('.input_fields_container').append('<div class="el" id='el" + id +"'>
<div class="form-group">
<label class="col-lg-2 control-label">#lang('main.test')</label>
<div class="col-lg-6"><input type="text" name="test[]" class="form-control"></div>
</div>
<div class="form-group"><label class="col-lg-2 control-label"></div>
</div>
<div>
#lang('main.delete')
</div>
</div>');
}
});
And then you can add the deletInput function like this code below, in this function the method finds div with the id of el+id and remove it:
function deleteInput(id){
$('#el'+id+'').remove();
}
Remember your id for el element must be unique.
This is the concept of removing inputs by id.
Hope this would help!

need help regarding submit event

I am trying to develop a form. Before submitting to server i validate it using jquery, everything is working fine except function on submit event, form is being submitted with errors, while checking in console window, error is like this, "unreachable code after return statement",please give some suggestions
Excerpt of html:
<form name="empform" action="editformProcess.php" method="POST" id="empform1"><a name="profileform1"></a>
<div class="row">
<div class="col-md-5 box"><label>First Name </label></div>
<div class="col-md-7 boxinput"><span class="colenSpan">: </span><input type="text" name="firstName" id="fName" required /></div>
</div>
<div class="row ErrorMessg">
<div class="col-md-5 "></div>
<div class="col-md-7 " id="firstNameErrorMsg"> </div>
</div>
<div class="row">
<div class="col-md-5 box"><label>Last Name </label></div>
<div class="col-md-7 boxinput"><span class="colenSpan">: </span><input type="text" name="lastName" /></div>
</div>
<div class="row">
<h3>Contact Details </h3>
<div class="col-md-5 box"><label>Email Id </label></div>
<div class="col-md-7 boxinput"><span class="colenSpan">: </span><input type="email" name="emailId" required /></div>
</div>
<div class="row">
<div class="col-md-5 box"><label>Mobile Number </label></div>
<div class="col-md-7 boxinput"><span class="colenSpan">: </span><input type="text" name="mobileNumber" id= "mobNum" required /></div>
<div id="mobbox"></div>
</div>
<div class="row ErrorMessg">
<div class="col-md-5"><label></label></div>
<div class="col-md-7" id="mobileNumMess"> </div>
<div id="mobbox"></div>
</div>
<input type="submit" name="submitDetails" value="Submit Details" id="submit"/>
</form>
excerpt of jquery:
$(function(){
//firstNameErrorMsg
$("#firstNameErrorMsg").hide();
$("#mobileNumMess").hide();
var errorFirstName= false;
var mobileNum= false;
$("#fName").focusout(function(){
checkFirstName();
});
$("#mobNum").focusout(function(){
checkMobNum();
});
function checkFirstName(){
var fNameLength = $("#fName").val().length;
if(fNameLength < 5 || fNameLength > 20){
$("#firstNameErrorMsg").html("sholud be between 5-20 charecters ");
$("#firstNameErrorMsg").show();
errorFirstName= true;
}else
{
$("#firstNameErrorMsg").hide();
}
}
function checkMobNum(){
var pattern = new RegExp(/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/);
if(pattern.test($("#mobNum").val())){
$("#mobileNumMess").hide();
}else{
$("#mobileNumMess").html("Invalid Mobile Number");
$("#mobileNumMess").show();
mobileNum = true;
console.log("h from begin sub");
}
}
$("#empform1").on('submit',function(){
//return true;
//console.log("h from begin2 sub1");
var errorFirstName= false;
var mobileNum= false;
checkFirstName();
checkMobNum();
//console.log("under var");
if(errorFirstName == false){
return true;
console.log("under if");
}else{
return false;
}
})
});
You need to correct your code in 2 places.
To solve form submit issue, you need to remove the variable declaration inside submit method
$("#empform1").on('submit',function(){
//return true;
//console.log("h from begin2 sub1");
//var errorFirstName= false;
//var mobileNum= false;
Dont forget to reset the var errorFirstName inside checkFirstName method
} else {
$("#firstNameErrorMsg").hide();
errorFirstName = false;
}]
When an expression exists after a valid return statement, a warning is given to indicate that the code after the return statement is unreachable, meaning it can never be run. Here,
if(errorFirstName == false){
return true;
console.log("under if");
}
is the error. The string is being logged after the return statement. Change this to:
if(errorFirstName == false){
console.log("under if");
return true;
}
I hope this was should fix it, though I am not able to reproduce the error.
Referring to any problems with submit, here's how I would suggest you edit the code:
function checkFirstName(){
var fNameLength = $("#fName").val().length;
if(fNameLength < 5 || fNameLength > 20){
$("#firstNameErrorMsg").html("sholud be between 5-20 charecters ");
$("#firstNameErrorMsg").show();
return true;
}else
{
$("#firstNameErrorMsg").hide();
return false
}
}
function checkMobNum(){
var pattern = new RegExp(/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/);
if(pattern.test($("#mobNum").val())){
$("#mobileNumMess").hide();
return false;
}else{
$("#mobileNumMess").html("Invalid Mobile Number");
$("#mobileNumMess").show();
console.log("h from begin sub");
return true;
}
}
$("#empform1").on('submit',function(){
var errorFirstName= checkFirstName();
var mobileNum= checkMobNum();
if(errorFirstName == false){
return true;
console.log("under if");
}else{
return false;
}
})
What you apparently intended to do with the code was to modify the errorFirstName and mobileNum in the scope of the function (the event handler) according to the check functions. But it doesn't work that way.
When you changed the variables in the check functions, the global variable was referred first of all. That's not something I guess you had intended.
As a good practice, I suggest you return the test results, as I have in the edited code.
This problem could also be solved by removing the lines of code which declares local variables with the same name in the handler function.

Categories