I have a specific problem where I need to render a html string from the server and show it to the user. The user then clicks the checkboxes and I transform it back into a html string and save it on the server.
Problem is after the user clicks the checkboxes, the transformed HTML string does not contain the checked attribute.
Here is a snippet
$("button").on("click", function(){
console.log($("#container").html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<input type="checkbox" id="checkbox"/>
<button> Test </button>
</div>
But when I manually click the checkbox and click the button and examine the console log, the checked attribute inside the HTML string is not seen.
How can I solve this problem?
Set checked attribute manually by .attr('checked', 'checked') on change:
$("button").on("click", function() {
console.log($("#container").html());
});
$('#checkbox').change(function() {
if ($(this).is(':checked')) {
$(this).attr('checked', 'checked');
} else {
$(this).removeAttr('checked');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<input type="checkbox" id="checkbox" />
<button> Test </button>
</div>
When you check a checkbox manually, the checked HTML attribute doesn't change.
You can change it yourself by selecting every checked checkbox and manually updating them with the jQuery :checked selector:
$('#container input[type="checkbox"]:checked').attr('checked','true');
$("button").on("click", function() {
$('#container input[type="checkbox"]:checked').attr('checked','true');
console.log($("#container").html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<input type="checkbox" id="checkbox" />
<button> Test </button>
</div>
Related
Why is my code not working? i need to simulate click on radio button. Radio button has click event.
$(".form-group").click(function() {
alert("clicked")
$(this).closest(".hotelObj", function() {
$(this).trigger("click");
})
});
.form-group {
background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label for="male" style="font-weight:800;">chose
<input type="radio" value="z6" class="hotelObj" name="hotelType">
<p>description</p>
</label>
</div>
Given the markup you've provided, javascript isn't necessary for this task, unless there's some other requirement you've left out.
Since the label contains all the area that you want the click handler to affect, it should just work as is (clicking anywhere in the pink box will cause the radio button to become selected).
.form-group {
background-color: pink;
}
<div class="form-group">
<label style="font-weight:800;">chose
<input type="radio" value="z6" class="hotelObj" name="hotelType">
<p>description</p>
</label>
</div>
Your code is not working because you are using .closest() jquery method which will look for element starting from itself and then up in DOM tree.
This way element with class.hotelObj is never found.
You need to use .find() method to find .hotelObj, because it's inside .form-group.
$(".form-group").click(function() {
$(this)
.find(".hotelObj")
.trigger("click");
});
Try onClickHandled property
<input type="checkbox" onclick="onClickHandler()" id="box" />
<script>
function onClickHandler(){
var chk=document.getElementById("box").value;
//use this value
}
</script>
I am a beginner in javascript, hopefully you can help me with this problem..
I have 2 buttons in html form and 1 checkbox, 1 button should be hidden and the other is visible. My problem is how to show the hidden button and hide the visible button at the same time when the checkbox is checked..
I know how to hide/show the button flip-ch1 but I can't do it to other button.
I have a script here:
$(document).ready(function() {
$('#flip-ch1').hide();
$('#radio').mouseup(function() {
$('#flip-ch1').toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="checkbox" name="radio" id="radio">
<button class="btn_style" id="ch1">Add</button>
<button class="btn_style" id="flip-ch1">Add</button>
</div>
Toggle them both:
<script type="text/javascript">
$(document).ready(function(){
$('#flip-ch1').hide();
$('#radio').mouseup(function () {
$('#ch1').toggle();
$('#flip-ch1').toggle();
});
});
</script>
Just add this line:
$('#ch1').toggle();
So, the complete js code would be:
$(document).ready(function () {
$('#flip-ch1').hide();
$('#radio').mouseup(function () {
$('#flip-ch1').toggle();
$('#ch1').toggle();
});
});
Do not get confused by the .hide(). It is used to hide one of the buttons only in the beginning. No need to use afterwards. The reason that you do not see any changes after toggling the checkbox, is that when first button is hidden the second one gets its place, the place does not remain empty. You can spot all this that I mentioned on inspect element of any major browser.
Try $('#radio').is(':checked') as below
$(document).ready(function() {
$('#flip-ch1').hide();
$('#radio').on('change', function() {
if ($('#radio').is(':checked')) {
$('#flip-ch1').show();
$('#ch1').hide();
} else {
$('#flip-ch1').hide();
$('#ch1').show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="checkbox" name="radio" id="radio">
<button class="btn_style" id="ch1">Add 1</button>
<button class="btn_style" id="flip-ch1">Add 2</button>
</div>
I'm working on a project where a button needs to be disabled until a hyperlink is clicked and a checkbox is checked. I currently have the checkbox part down using jQuery:
$('#tc-checkbox').change(function(){
if($(this).is(":checked")) {
$('#tc-btn').removeClass('tc-disable');
} else {
$('#tc-btn').addClass('tc-disable');
}
});
But I also need to set it up so the class of tc-disable is still on the button until an anchor tag is clicked as well. I've never really done this before where a link needs to be clicked before removing a class and couldn't find what I was looking for as I was Googling for an answer.
Hope the code below helps. I also added console out put so you can track the value. Another option is use custom attribute on link element instead of javascript variable to track if the link is clicked.
var enableLinkClicked = false;
$('#tc-link').click(function() {
enableLinkClicked = true;
console.log("link clicked\ncheckbox value: " + $($('#tc-checkbox')).is(":checked"));
console.log("link clicked: " + enableLinkClicked);
if ($('#tc-checkbox').is(":checked")) {
$('#tc-btn').removeClass('tc-disable');
}
});
$('#tc-checkbox').change(function() {
console.log("checkbox clicked\ncheckbox value: " + $(this).is(":checked"));
console.log("link clicked: " + enableLinkClicked);
if ($(this).is(":checked") && enableLinkClicked) {
$('#tc-btn').removeClass('tc-disable');
} else {
$('#tc-btn').addClass('tc-disable');
}
});
#tc-btn.tc-disable {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<button id="tc-btn">My Button</button>
<br/>
<a id="tc-link" href="javascript:void(0);">Link to enable button</a>
<br/>
<input type="checkbox" id="tc-checkbox" />
If the page is refreshing or taking you to a different page when you click the hyperlink, you will want to look into sessionStorage. When the hyperlink is clicked you will want to set a sessionStorage variable and when the page loads you want to check that variable to see if it is populated. If the variable is populated, enable the button.
Set the variable.
sessionStorage.setItem('key', 'value');
Get the variable
var data = sessionStorage.getItem('key');
If you need to re-disable the button you can clear the session storage and reapply the disabled class.
sessionStorage.clear();
You can learn more about session storage here.
If the page does not refresh you could just set an attr on the link when it is clicked like so.
$('#tc-link').on('click', function() {
$(this).attr('clicked', 'true');
});
Then when the checkbox is checked you can check this in your function.
$('#tc-checkbox').change(function(){
if($(this).is(":checked") && $('#tc-link').hasAttr('clicked')) {
$('#tc-btn').removeClass('tc-disable');
} else {
$('#tc-btn').addClass('tc-disable');
}
});
These are just some solutions I could think of off the top of my head. Hope this helps.
Maybe this is better for you. First you make an .on('click' event listener on the anchor element, then, if the checkbox is checked enable the button. I added the else statement to disable the button if a user clicks the link and the checkbox is not set for an example. In this example you don't need the classes.
But if you needed to keep the the classes then you would replace the $('#tc-btn').prop('disabled', false); with $('#tc-btn').addClass() or .removeClass()
$( '#theLink' ).on( 'click', function(e)
{
e.preventDefault();
if($('#tc-checkbox').is(':checked'))
{
$('#tc-btn').prop('disabled', false);
$('#tc-btn').val('Currently enabled');
}
else
{
$('#tc-btn').val('Currently disabled');
$('#tc-btn').prop('disabled', true);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="tc-checkbox" />
This link will enable the button
<input type="button" id="tc-btn" value="Currently disabled" disabled="disabled"/>
Here a much more simple solution and it handles the state of the button if they uncheck the "I Accept" checkbox. It is pretty easy to implement. I just used Bootstrap to pretty up the example.
//Handles the anchor click
$("#anchor").click(() => {
$("#anchor").addClass("visited");
$("#acceptBtn").prop("disabled", buttonState());
});
//Handles the checkbox check
$("#checkBx").on("change", () => {
$("#acceptBtn").prop("disabled", buttonState());
});
//Function that checks the state and decides if the button should be enabled.
buttonState = () => {
let anchorClicked = $("#anchor").hasClass("visited");
let checkboxChecked = $("#checkBx").prop("checked") === true;
return !(anchorClicked && checkboxChecked);
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-md-12">
View Terms
</div>
</div>
<div class="row">
<div class="col-md-12">
<label class="form-check-label">
<input class="form-check-input" id="checkBx" type="checkbox" value="">
I accept the terms
</label>
</div>
</div>
<div class="row">
<div class="col-md-12">
<button id="acceptBtn" class="btn btn-success" disabled="disabled">
Ok
</button>
</div>
</div>
</div>
A one-liner solution using Javascript could be:
<input type="submit" id="test" name="test" required disabled="disabled">
<label for="test">I clicked the <a target="_blank" href="https://stackoverflow.com" onclick="document.getElementById('test').disabled=false">link</a>.</label>
Change the type "submit" to "button" or "checkbox" accordingly to your needs.
TL;DR:
I use $(..).append(node), but newly added nodes are not considered for inclusion despite them (supposedly) matching jQuery selectors.
Question
I have some code below that uses checkboxes but emulates radio button behavior. In other words, only one checkbox can (validly) be selected at any time. No more than one should be selected.
If you run the example below and click on the first 3 checkboxes, they will behave like radio buttons. Only one will be selected, no matter how many you click.
However, if you Add Point, newly added points will not be considered for the JS even though in theory it should grab them too...
Specifically: You can select the newly added checkbox, and it will be selected in addition to one already selected previously. That is incorrect as only 1 should be selected at any time and all others should be unselected.
What is happening and how can I have newly added nodes be included into jQuery selectors?
$(function() {
//check first box
$("input.duty:first").prop("checked", true);
//clicking unchecked box should check that box
//unchecks all others
$(".duty").on('click', function(event) {
$("input.duty").prop("checked", false);
$(this).prop("checked", true);
});
$("#addCasePoint").on("click", function() {
var newRowIndex = $('#newRowIndex').text();
var template = $('#casePointTemplate').data('template');
template = template.replace(/__index__/g, newRowIndex);
$('#casePointsFieldset').append(template);
$('#newRowIndex').text(++newRowIndex);
return false;
});
//deletes case point
$("#selection").on("click", ".removeCase", function() {
var caseCount = $('#selection .casePointFieldset').length
if (caseCount === 1) return false; //keep at least one row
$(this).closest("fieldset").remove();
return false;
});
});
.casePointFieldset {
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="selection">
<fieldset id="casePointsFieldset">
<legend>Case Points</legend>
<div id="pointFieldset">
<fieldset class="casePointFieldset">
<div>
<label><span>Duty:</span> <input name="point[1]" class="duty" value="1" type="checkbox"></label>
</div>
<button class="removeCase">Remove</button>
</fieldset>
<fieldset class="casePointFieldset">
<div>
<label><span>Duty:</span> <input name="point[1]" class="duty" value="1" type="checkbox"></label>
</div>
<button class="removeCase">Remove</button>
</fieldset>
<fieldset class="casePointFieldset">
<div>
<label><span>Duty:</span> <input name="point[1]" class="duty" value="1" type="checkbox"></label>
</div>
<button class="removeCase">Remove</button>
</fieldset>
</div>
<!-- include template -->
<span id="casePointTemplate" data-template="<fieldset class="casePointFieldset"><div><label><span>Duty:</span> <input name="point[__index__]" class="duty" value="1" type="checkbox"></label></div><button class="removeCase">Remove</button></fieldset>">
</span>
</fieldset>
<button id="addCasePoint">Add Point</button>
</form>
The problem is how you're binding to them. The .click function (or .on('click')) basically works like this:
Find all of the currently existing elements which match a selector ($('.your.selector.here'))
Attach an event handler to each of those elements
Notice how I mentioned it binds to ones which already exist? That means it won't bind to newly created ones automatically. However, you can use .on to bind to the parent of those elements then listen for events on a selector. I'll show you what I mean:
$('#addItem').click(function() {
$('.container').append('<button class="item">Item</button>');
});
// Notice that I'm binding to the parent
// then specifying which events from it's children
// I want to listen to (click events from .item elements)
$('.container').on('click', '.item', function() {
console.log("I'm an item");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<button class="item">Item</button>
</div>
<button id="addItem">Add New Item</button>
If you change your on('click' to work like that then you'll have no problems.
Easiest way will be, attaching the event to the document. In the past this was done with the live() method.
$(document).on('click', '.duty', function(event) {
$("input.duty").prop("checked", false);
$(this).prop("checked", true);
});
I want to display the same div with different heading by checkbox hide/show.
$('#cbxShowHide').click(function() {
this.checked ? $('#block').show(1000) : $('#block').hide(1000);
});
#block {
display: none;
background: #eef;
padding: 10px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="cbxShowHide" />
<label for="cbxShowHide">Show/Hide</label>
<input type="checkbox" id="cbxShowHide1" />
<label for="cbxShowHide1">Show/Hide1</label>
<input type="checkbox" id="cbxShowHide2" />
<label for="cbxShowHide2">Show/Hide2</label>
<div id="block">Some text here</div>
in the above example on clicking on checkbox "Show/Hide"I am able to display the text "Some text here".
I want to do this for nth checkbox so that I can show "some text here" nth time like "some text here1", "some text here2"
refer the this jsfiddle. I have moved the content inside div in span
$('#cbxShowHide1').click(function(){
$('#block span').text("yyour new text for this div")
this.checked?$('#block').show(1000):$('#block').hide(1000);
});
Hope this helps
You are getting the click event only for a specific ID "cbxShowHide"
I changed it so the event would be from all input which ever is clicked
$('[type~=checkbox]').click(function(){
this.checked?$('#block').show(1000):$('#block').hide(1000);
});
$('[type~=checkbox]').click(function(){
this.checked?$('#block').show(1000):$('#block').hide(1000);
});
#block{display:none;background:#eef;padding:10px;text-align:center;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="cbxShowHide"/><label for="cbxShowHide">Show/Hide</label>
<input type="checkbox" id="cbxShowHide1"/><label for="cbxShowHide">Show/Hide1</label>
<input type="checkbox" id="cbxShowHide2"/><label for="cbxShowHide">Show/Hide2</label>
<div id="block">Some text here</div>
First thing is that you need to use a class instead of an ID, then it will do that function for each individual checkbox,
Secondly remember that a for tag is specific to an ID so if you link an label to a checkbox make sure the two match.
Hope this example helps
$('.checkbox').click(function(){
if($(this).attr('id') == 'cbxShowHide')
{
$('#block').text('Some text here')
}
if($(this).attr('id') == 'cbxShowHide1')
{
$('#block').text('Some text here1')
}
if($(this).attr('id') == 'cbxShowHide2')
{
$('#block').text('Some text here2')
}
this.checked?$('#block').show(1000):$('#block').hide(1000);
});
#block{display:none;background:#eef;padding:10px;text-align:center;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="checkbox" class='checkbox' id="cbxShowHide"/><label for="cbxShowHide">Show/Hide</label>
<input type="checkbox" class='checkbox' id="cbxShowHide1"/><label for="cbxShowHide1">Show/Hide1</label>
<input type="checkbox" class='checkbox' id="cbxShowHide2"/><label for="cbxShowHide2">Show/Hide2</label>
<div id="block">Some text here</div>
Not so elegant, but i don't have much time..i hope i got what you meant
CSS
#block, #block1, #block2 {display:none;background:#eef;padding:10px;text-align:center;}
HTML
<input type="checkbox" id="cbxShowHide"/><label for="cbxShowHide">Show/Hide</label>
<input type="checkbox" id="cbxShowHide1"/><label for="cbxShowHide">Show/Hide1</label>
<input type="checkbox" id="cbxShowHide2"/><label for="cbxShowHide">Show/Hide2</label>
<div id="block"><span>Some text here</span></div>
<div id="block1"><span>Some text here 1</span></div>
<div id="block2"><span>Some text here 2</span></div>
JS
$('#cbxShowHide').click(function(){
this.checked?$('#block').show(1000):$('#block').hide(1000);
});
$('#cbxShowHide1').click(function(){
this.checked?$('#block1').show(1000):$('#block1').hide(1000);
});
$('#cbxShowHide2').click(function(){
this.checked?$('#block2').show(1000):$('#block2').hide(1000);
});
Try this Jsfiddle :jsfiddle.net/xs523nw8/6/
$("input[type='checkbox']").click(function(){
if($(this).is(":checked")){
$(this).siblings("input[type='checkbox']").removeAttr("checked");
$("#block").text('Some Text Here :'+$(this).index());
$("#block").show(1000)
}
else{
$("#block").hide(1000);
}
});
Check this fiddle https://jsfiddle.net/tz5ror3s/
I have added a class in checkboxes and bind click event on them and printing text inside block span.
$('.cbxShowHide').click(function() {
$('#block span').text('Some text here ' + $(".cbxShowHide:checked").length );
$('#block').show();
});
1. Toggling element's text
fiddle
Case: you want to just toggle the #block element text.
Fiddle uses type='radio' inputs rather than type='checkbox', as you have only one place where you toggle text, so selecting only one option at the time is better way to do it.
2. Showing elements based on checked checkboxes
fiddle
Case: you want multiple boxes hidden/shown based on checkbox input state(checked/unchecked).
On every state change, it loops through the checkboxes and:
For every checked one, it selects box with the same number and shows it
For every unchecked one, it select box with the same number and hides it