I have this function to toggle the display of the text when clicked, but I have about 5 different of these in my application where everything is called different ID's, is there a way of doing that without having to create 5 different functions?
This is my attempt of doing it given the ID but am not sure on how to do without, but the issue i am getting when doing all is it will toggle all 5 at the same time, when its meant to be one by 1
$('#isAgeSelected').click(function() {
$("#txtAge").toggle(this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">Age is something</div>
Or, is there a different way in doing it in vb.net?
All help is appreciated :)
You can add a data- attribute to the checkbox, containing the ID of the element you want toggled.
(Note that I changed the ID isAgeSelected to a class; IDs should always be unique, since JavaScript will only select the first instance of an ID that it finds.)
$('.isAgeSelected').click(function() {
$($(this).data('toggle')).toggle(this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" data-toggle="#txtAge" class="isAgeSelected"/>
<input type="checkbox" data-toggle="#txtAge2" class="isAgeSelected"/>
<div id="txtAge" style="display:none">Age is something</div>
<div id="txtAge2" style="display:none">Age is nothing</div>
You don't need the ID to select the checkboxes, use a generic class instead.
This solution relies on the fact that the text is the next sibling of the checkbox.
$('.isAgeSelected').click(function() {
$(this).next().toggle(this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="isAgeSelected"/>
<div class="txtAge" style="display:none">1Age is something</div>
<input type="checkbox" class="isAgeSelected"/>
<div class="txtAge" style="display:none">2Age is something</div>
<input type="checkbox" class="isAgeSelected"/>
<div class="txtAge" style="display:none">3Age is something</div>
Use a function. Like so:
function doSomething(firstObjectSelector, secondObjectSelector){
$(firstObjectSelector).click(function() {
$(secondObjectSelector).toggle(this.checked);
});
}
Usage:
doSomething('#isAgeSelected', '#isAgeSelected'); //using ids
or
doSomething('.isAgeSelected', '.isAgeSelected'); //using classes
or
doSomething('div', 'span'); //using tags
Related
I try to change a text insert in an div box with jquery. Here is the Code:
<div onClick="$(this span).text('My new Text');" class="switch switch-success" style="float: right;">
<label>
<input type="checkbox"><span>Yes</span>
</label>
</div>
I want to change this "Yes" to "No". Thanks for help ;)
Use the .find method
See a working fiddle here
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div onClick="$(this).find('span').text('My new Text');" class="switch switch-success" style="float: right;">
<label>
<input type="checkbox"><span>Yes</span>
</label>
</div>
You have two options.
Pass this a second parameter which is context
$('span', this).text('My new Text');
Get this element and that use find to get span in it.
$(this).find('span').text('My new Text');
Please separate structure, style and function - the CSS, HTML and JS should not be in the same space - its always better to separate the code for better code quality.Also you could do a toggle for the states of the checkbox so that there is different text on the "checked" and "not checked" states.
And you can even do that with CSS
$('.switch').click(function(){
$(this).find('span').text('My new Text')
})
.switch{float: right}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="switch switch-success" >
<label>
<input type="checkbox"><span>Yes</span>
</label>
</div>
In this code I am checking the chekbox with class disableDivCheckbox and the code is disabling all of the div content with class disableDiv. But if I apply this combination to another checkbox and another div, this is not working properly. So I want to find closest div with class disableDiv and disable only that div. I am using disabale * because I want to disbale div and its contents.
$(".disableDivCheckbox").click(function () {
if ($(this).is(":checked")) {
$('.disableDiv *').removeAttr("disabled");
}
else {
$('.disableDiv *').val('').prop('checked', false).attr("disabled", "disabled");
}
});
fiddle : https://jsfiddle.net/8c0x1pho/
You can try this approach:
Get checked state and save it in a variable
Navigate to all necessary elements using this. It will make your code more modular.
Try not to use * selector. Use more specific selectors as this will specify element types you are manipulating and make your code more reusable.
Instead of attr and removeAttr, you can just set value of disabled as true or false . You can just use !$(..).is(":checked")
Sample:
// Only call functions. DON'T declare any functions in ready.
$(document).ready(function() {
// Have a common function.
// If size grows, this can be exported to its own file
registerEvents();
// Initialise on load states.
updateUIStates("#addBusinessObjectivesCheckbox")
});
function registerEvents() {
$(".disableDivCheckbox").click(function() {
updateUIStates(this)
})
}
function updateUIStates(el) {
var isNotChecked = !$(el).is(":checked");
var inputs = $(el)
.parents(".checkbox")
.siblings(".disableDiv")
.find('input');
inputs.attr("disabled", isNotChecked)
isNotChecked && inputs.val('').prop('checked', false)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<fieldset id="AddBusinessObjectivesFieldset" class="">
<legend>
Add business objectives
</legend>
<div class="checkbox">
<label>
<input type="checkbox" value="addBusinessObjectivesCheckbox" name="addBusinessObjectivesCheckbox" class="disableDivCheckbox" id="addBusinessObjectivesCheckbox"> Add business objectives
</label>
</div>
<div style="border: 2px solid;margin-bottom: 5px;border-color: gray;padding: 0px 0px 0px 5px;margin-top: 5px;margin-right: 10px;" class="disableDiv">
<div class="form-inline" style="margin-top:5px;margin-bottom:5px;">
<table>
<tr>
<td>
<div class="radio">
<label>
<input type="radio" name="AddBusinessObjectives" id="" value="0" class=""> Fixed N
</label>
</div>
</td>
<td>
<div class="radio">
<label>
<input type="radio" name="AddBusinessObjectives" id="" value="1" class=""> Random upto N
</label>
<input type="text" placeholder="Enter N" id="indexTextboxAddBusinessObjectives" name="indexTextboxAddBusinessObjectives" style="width:70px" class="" />
</div>
</td>
</tr>
</table>
</div>
</div>
</fieldset>
Pointers
$(document).ready() is more like init function. Try to call functions instead of defining in it. This will make easier to understand as it will depict a flow.
Use pure functions and call then. Like onChange, you can call few functions: updateUIStates(), postDataToServer(), processResponse(), otherTodos(). This may look like overkill but in long run this will help.
Create a tree structure in your markup.
<div class="container">
<div class="checkbox-container">...</div>
<div class="input-containers">...</div>
</div>
This will ease navigation part. No matter what structure you use, keep it standardised. This will keep your JS clean.
Try this,
$(".disableDivCheckbox").click(function () {
if ($(this).is(":checked")) {
$(this).closest('.disableDiv *').removeAttr("disabled");
} else {
$(this).closest('.disableDiv *').val('').prop('checked', false).attr("disabled", "disabled");
}
});
This means that, you will disable all content of only that disableDiv class to which disableDivCheckbox belongs.
Give it a try, this will work.
I asked how to select more checkbox by value, and it works well.
See here the question: Select more checkbox by value or id
But now I would like to know if you can select these checkboxes if I have 2 divverenti div, here is an example:
<div class="checkbox_option1">
<div class="icheckbox" style="position: relative;">
<input class="checkbox_filter" type="checkbox" id="ffQHb" value="Italy">
<input class="checkbox_filter" type="checkbox" id="ffQrt" value="Germany">
<input class="checkbox_filter" type="checkbox" id="ffQzx" value="France">
</div>
</div>
<div class="checkbox_option2">
<div class="icheckbox" style="position: relative;">
<input class="checkbox_filter" type="checkbox" id="ffQHb" value="Italy">
<input class="checkbox_filter" type="checkbox" id="ffQrt" value="Germany">
<input class="checkbox_filter" type="checkbox" id="ffQzx" value="France">
<input class="checkbox_filter" type="checkbox" id="ffQzx" value="France">
</div>
</div>
I would like that the toggle select only those of the <div class="checkbox_option2"> it's possible? Many Thanks
Check out jQuery child selectors, I think it will be of use: https://api.jquery.com/child-selector/
Building off the solution to your prior question, you would use something along these lines:
var check_germany = $(".checkbox_option2 > input:checkbox[value=Germany]");
Yes use parent-child selectors (using >) if they're direct children like:
$("div.checkbox_option2 > input:checkbox[value=Germany]")...
Or just a space () if they're children or children of children ...etc like:
$("div.checkbox_option2 input:checkbox[value=Germany]")...
In your case the second one will work.
More about CSS selectors here.
I'm about lose my mind with this problem. No form of jQuery selector seems to work in dynamically finding any elements above the link. I'm trying to access an element above the link and hide it. Using things like parent(), prev(), before(), closest(), ect. will show a non-null object but it won't respond to the hide() method.
<div class="row">
<div class="col-xs-5">
<div id="test_fields">
<li id="test_input" class="string input optional stringish">
<label class="label" for="test_input">Ingredient name</label>
<input type="text" name="test_input" value="afsfasf" id="test_input">
</li>
</div>
<input type="hidden" id="recipe_recipe_ingredients_attributes_0__destroy" name="recipe[recipe_ingredients_attributes][0][_destroy]">
Remove Ingredient
</div>
</div>
function remove_fields(link)
{
$(link).prev("input[type=hidden]").val('1'); // this doesn't work
var divToHide = $(link).prev('div');
$(divToHide).hide() // this doesn't work
//$('#test_fields').hide(); //this works
}
Try replacing the link as below:
Remove Ingredient
I'm not sure. But maybe this is the problem. Because I remember that I have had problem with 'this'previously and when I replaced that, it performed the job.
you can try .closest() and .find()
function remove_fields(link) {
$(link).closest('div[class^="col-xs"]').find("input[type=hidden]").val('1');
var div_to_hide = $(link).closest('div[class^="col-xs"]').find('#test_fields');
$(div_to_hide).hide();
//$('#test_fields').hide(); //this works
}
You can't change hidden input's "value" attribute by using .val(). You need to use:
$(link).prev("input[type=hidden]").attr('value', '1');
As I'm not really sure what do you want to do with this input, I'll just let it go like this.
.prev() fn goes only one previous element in the structure. As input is a <a>'s previous element, you can't select div like that. You can use .siblings() for instance.
$(link).siblings('div').hide();
If you break the code in pieces, it gets easier.
First I took the 'Link', from it I grabbed the nearest div above it, then I picked up the input.
I did not make many changes to your code.
function remove_fields(link)
{
var $link =$(link);
var $divToHide = $link.closest('div');
$divToHide.find("input[type='hidden']").val('1');
$divToHide.hide()
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="row">
<div class="col-xs-5">
<div id="test_fields">
<li id="test_input" class="string input optional stringish">
<label class="label" for="test_input">Ingredient name</label>
<input type="text" name="test_input" value="afsfasf" id="test_input">
</li>
</div>
<input type="hidden" id="recipe_recipe_ingredients_attributes_0__destroy" name="recipe[recipe_ingredients_attributes][0][_destroy]">
Remove Ingredient
</div>
</div>
I have the following form :
<form class="form-inline" role="form">
<div class="col-xs-3">
<div class="pic-container">
<div class="checkbox">
<label>
<input type="checkbox" name="discounting" onchange='handleChange(this);' id='check11' > Show only price-discounted products
</label>
</div>
</div>
</div>
<div class="col-xs-3">
<div class="pic-container">
<div class="checkbox" id='check21'>
<label>
<input type="checkbox" name="discounting" onchange='' id='check21'> Show only price-discounted products
</label>
</div>
</div>
</div>
</form>
I'd like to be able to check the second checkbox automatically with JavaScript once I check the first one. I tried using the following script :
<script>
function handleChange(cb) {
if(cb.checked == true) {
alert('Message 1');
document.getElementById("check21").checked = true;
} else {
alert('Message 2');
var x = document.getElementById("check21").disabled= false;
}
}
</script>
But it doesn't work since I think with bootstrap is a question of classes.
The problem as Didier pointed out is that you have two elements with the same ID:
<div class="checkbox" id='check21'>
and
<input type="checkbox" name="discounting" onchange='' id='check21'>
The call to document.getElementById('check21') will probably (because the behavior is undefined) return the first one, which in this case is the <div> element, not the checkbox.
You must not use the same ID on two HTML elements, so you need to change the ID on one or the other of them.
http://jsfiddle.net/uywaxds5/2/
I included boostrap as an external reference.
<div class="checkbox" id='check22'>
<label>
<input type="checkbox" name="discounting" onchange='' id='check21'> Show only price-discounted products
</label>
</div>
Fixing the duplicate id seems to work.
If it does not works, the issue might be in another part of your code.
Use a different name for the second radio button
<input type="checkbox" name="discounting21">
There can only be one selected radio button belonging to the same group(ie. name).