How to Add text after checkbox - javascript

I have the following html:
<td><label class="checkbox-inline"><input type="checkbox" class="chkRootCauseSummary" /> </label></td>
How can i insert text into the label, without losing the checkbox?
Ive tried the following, but i lose the checkbox:
$('.chkRootCauseSummary').click(function () {
var num = $(this).closest('table').find('input[type=checkbox]:checked').length;
$(this).closest('label').append().html(num);
});

There is a much cleaner way to do it. Simply, while creating your checkbox add a value attribute (or an attribute with any name)
<input type="checkbox" class="chkRootCauseSummary" value="Some Value" />
and use CSS selector :after like
[type=checkbox]:after {
content: attr(value);
}

what you are looking for is a prepend since it needs to be added inside .checkbox-inline and outside .chkRootCauseSummary
Replace
$(this).closest('label').append().html(num);
with
$(this).closest('label').prepend(num);

try this
$('.chkRootCauseSummary').click(function() {
var num = $(this).closest('table').find('input[type=checkbox]:checked').length;
$(this).closest('label').after(num)
});

$('.chkRootCauseSummary').click(function () {
var num = $(this).closest('table').find('input[type=checkbox]:checked').length;
$(this).closest('label').after().html(num);
});

Related

Change parent style with javascript based on checked input

I am looking to change the style of the parent label when the checkbox is checked. I realise this can't feasibly be done with CSS, is this possible with Javascript?
<label id="cont">
<span>
<input type="checkbox" />
</span>
</label>
Yes, here's an example:
const container = document.querySelector('#cont');
const checkbox = document.querySelector('input');
checkbox.addEventListener('change', () => {
if (checkbox.checked) {
container.style.background = 'red'
} else {
container.style.background = 'white'
}
})
<label id="cont">
<span>
<input type="checkbox" />
</span>
</label>
Your question is a bit unclear. If you have just a single parent element and checkbox like your code suggests, then it's straightforward.
You can define the new styles you want a class(let's say a class called new-style) inside your stylesheet, then add a listener function inside your js script to trigger when the checkbox is clicked. The listener function will basically insert the class into the parent if it doesn't have it or remove it if it does. Something like this.
<script>
let checkbox = document.querySelector('input[type="checkbox"]');
checkbox.onclick = function() {
let parent = document.querySelector('#cont')
parent.classList.toggle('new-style');
}
</script>
Have you tried it this way? You can use css :checked property for this.
input:checked + label {
color: red;
}
<input id="name" type="checkbox">
<label for="name" id="cont">
label
</label>

jQuery function not executing when checkbox changed

Here's the code I'm working on:
$(document).ready(function(){
var rewrite= function() {
$("#numback_**SQL_Value**").attr("readonly" , "readonly");
$("#numback_**SQL_Value**").attr("value" ,function() { return ($(".Report_Box").size() +**SQL_Value**;)}
)};
$(".Report_Box").click(rewrite);
});
Report_Box is a class of checkboxes later in the code. When one of the checkboxes is changed, the rewrite function is supposed to trigger.
Rewrite is supposed to lock the numback input box, turning it read only as I set the value to the number of Report_Box'es clicked.
I simplified your code to this - and it worked ok. I added the code you can use to make the input readonly...
See the description of using prop not attr here:
Setting a control to readonly using jquery 1.6 .prop()
<div>
<input type="checkbox" class="Report_Box"/>
<input type="checkbox" class="Report_Box"/>
<input type="checkbox" class="Report_Box"/>
<input type="checkbox" class="Report_Box"/>
<input type="checkbox" class="Report_Box"/>
<input type="text" id="makero"/>
<script>
$(document).ready(function(){
var rewrite= function() {
$('#makero').val($(".Report_Box").size()).prop('readonly', true);
console.log($(".Report_Box").size());
};
$(".Report_Box").click(rewrite);
});
Could it be the typos that is causing your trouble? Try this:
$("#numback_**SQL_Value**").attr("value", function() { return($(".Report_Box").size()+"**SQL_Value**");} )};

jQuery :empty not working with input

I am having a problem in using jQuery's :empty pseudo selector. Basically, it isn't working on inputs the way I think it should. Given this html, I'm trying to get a count of all the inputs which don't have values without a loop.
<div id="sampleDiv">
<label>My first Input:</label>
<input name="test" id="firstInput" type="text" value="default text" /><br/><br/>
<label>My second Input:</label>
<input name="test" id="secondInput" type="text" value="" /><br/><br/>
<label>My third Input:</label>
<input name="test" id="thirdInput" type="text" value="" />
I'm using a selector like this
$('#sampleDiv input:empty').length
but it's returning 3, including the one with the value. Here is the fiddle and thanks for any help here!:
https://jsfiddle.net/chas688/b5fad3Lu/
The :empty selector is designed to look through the children of an element. This is why it doesn't necessarily work for you in this instance. Instead, you can select by the value attribute:
$('#sampleDiv input[value=""]').length;
Example
Or by filter():
$('#sampleDiv input').filter(function() {
return this.value == '';
}).length;
Example
The :empty stands for empty HTML and not empty values! You have to use this way:
count = 0;
$('#sampleDiv input').each(function () {
if ($(this).val().length == 0)
count++;
});
Or use .filter():
$('#sampleDiv input').filter(function() {
return ($(this).val().trim().length == 0);
}).length;
This one works for all input text.
https://jsfiddle.net/b5fad3Lu/2/
var pl = $('input:text[value=""]').length;
$('#numberofEmpty').text( pl );

one textbox value in another textbox

I want to get value of one textbox and put the same in another textbox.
my code is :
<input type="text" value="Keyword" id="one" />
<input type="text" value="Search" id="two" />
button
jquery:
var input = $("#one");
$('#btn').click(function(){
alert('dgdhjdgj');
var oneValue = $('#one').val();
alert("one value "+ oneValue);
var twoVal = $('#two').val($(input).attr('value'));
alert('two Val' + twoVal);
});
demo is here.
Issue : when I change the value of textbox #one, it does not change the value of #two.
thanks in advance.
$(input).attr('value') gets the value of the value attribute, which is the initial value, not the current value.
You had it right two lines earlier. Use val().
Try this
HTML
<input type="text" placeholder="Keyword" id="one" />
<input type="text" placeholder="Search" id="two" />
button
Script
$('#btn').click(function() {
var oneValue = $('#one').val();
$('#two').val(oneValue)
})
Fiddle
write textarea and check it. JSFIDDLE
$("#add").click(function(){
var thenVal = $("#textarea_first").val();
$("#textarea_second").val(thenVal);
});
if all that you want to change the text of second textbox, as soon as you change the text of first textbox, just use jQuery's change event.
just try this then:
$('#one').on("change",function(){
$('#two').val($(this).val());
});

How can I know which radio button is selected via jQuery?

I have two radio buttons and want to post the value of the selected one.
How can I get the value with jQuery?
I can get all of them like this:
$("form :radio")
How do I know which one is selected?
To get the value of the selected radioName item of a form with id myForm:
$('input[name=radioName]:checked', '#myForm').val()
Here's an example:
$('#myForm input').on('change', function() {
alert($('input[name=radioName]:checked', '#myForm').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<fieldset>
<legend>Choose radioName</legend>
<label><input type="radio" name="radioName" value="1" /> 1</label> <br />
<label><input type="radio" name="radioName" value="2" /> 2</label> <br />
<label><input type="radio" name="radioName" value="3" /> 3</label> <br />
</fieldset>
</form>
Use this..
$("#myform input[type='radio']:checked").val();
If you already have a reference to a radio button group, for example:
var myRadio = $("input[name=myRadio]");
Use the filter() function, not find(). (find() is for locating child/descendant elements, whereas filter() searches top-level elements in your selection.)
var checkedValue = myRadio.filter(":checked").val();
Notes: This answer was originally correcting another answer that recommended using find(), which seems to have since been changed. find() could still be useful for the situation where you already had a reference to a container element, but not to the radio buttons, e.g.:
var form = $("#mainForm");
...
var checkedValue = form.find("input[name=myRadio]:checked").val();
This should work:
$("input[name='radioName']:checked").val()
Note the "" usaged around the input:checked and not '' like the Peter J's solution
You can use the :checked selector along with the radio selector.
$("form:radio:checked").val();
If you want just the boolean value, i.e. if it's checked or not try this:
$("#Myradio").is(":checked")
Get all radios:
var radios = jQuery("input[type='radio']");
Filter to get the one thats checked
radios.filter(":checked")
Another option is:
$('input[name=radioName]:checked').val()
$("input:radio:checked").val();
In my case I have two radio buttons in one form and I wanted to know the status of each button.
This below worked for me:
// get radio buttons value
console.log( "radio1: " + $('input[id=radio1]:checked', '#toggle-form').val() );
console.log( "radio2: " + $('input[id=radio2]:checked', '#toggle-form').val() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="toggle-form">
<div id="radio">
<input type="radio" id="radio1" name="radio" checked="checked" /><label for="radio1">Plot single</label>
<input type="radio" id="radio2" name="radio"/><label for="radio2">Plot all</label>
</div>
</form>
Here's how I would write the form and handle the getting of the checked radio.
Using a form called myForm:
<form id='myForm'>
<input type='radio' name='radio1' class='radio1' value='val1' />
<input type='radio' name='radio1' class='radio1' value='val2' />
...
</form>
Get the value from the form:
$('#myForm .radio1:checked').val();
If you're not posting the form, I would simplify it further by using:
<input type='radio' class='radio1' value='val1' />
<input type='radio' class='radio1' value='val2' />
Then getting the checked value becomes:
$('.radio1:checked').val();
Having a class name on the input allows me to easily style the inputs...
try this one.
it worked for me
$('input[type="radio"][name="name"]:checked').val();
In a JSF generated radio button (using <h:selectOneRadio> tag), you can do this:
radiobuttonvalue = jQuery("input[name='form_id\:radiobutton_id']:checked").val();
where selectOneRadio ID is radiobutton_id and form ID is form_id.
Be sure to use name instead id, as indicated, because jQuery uses this attribute (name is generated automatically by JSF resembling control ID).
Also, check if the user does not select anything.
var radioanswer = 'none';
if ($('input[name=myRadio]:checked').val() != null) {
radioanswer = $('input[name=myRadio]:checked').val();
}
If you have Multiple radio buttons in single form then
var myRadio1 = $('input[name=radioButtonName1]');
var value1 = myRadio1.filter(':checked').val();
var myRadio2 = $('input[name=radioButtonName2]');
var value2 = myRadio2.filter(':checked').val();
This is working for me.
I wrote a jQuery plugin for setting and getting radio-button values. It also respects the "change" event on them.
(function ($) {
function changeRadioButton(element, value) {
var name = $(element).attr("name");
$("[type=radio][name=" + name + "]:checked").removeAttr("checked");
$("[type=radio][name=" + name + "][value=" + value + "]").attr("checked", "checked");
$("[type=radio][name=" + name + "]:checked").change();
}
function getRadioButton(element) {
var name = $(element).attr("name");
return $("[type=radio][name=" + name + "]:checked").attr("value");
}
var originalVal = $.fn.val;
$.fn.val = function(value) {
//is it a radio button? treat it differently.
if($(this).is("[type=radio]")) {
if (typeof value != 'undefined') {
//setter
changeRadioButton(this, value);
return $(this);
} else {
//getter
return getRadioButton(this);
}
} else {
//it wasn't a radio button - let's call the default val function.
if (typeof value != 'undefined') {
return originalVal.call(this, value);
} else {
return originalVal.call(this);
}
}
};
})(jQuery);
Put the code anywhere to enable the addin. Then enjoy! It just overrides the default val function without breaking anything.
You can visit this jsFiddle to try it in action, and see how it works.
Fiddle
$(".Stat").click(function () {
var rdbVal1 = $("input[name$=S]:checked").val();
}
This works fine
$('input[type="radio"][class="className"]:checked').val()
Working Demo
The :checked selector works for checkboxes, radio buttons, and select elements. For select elements only, use the :selected selector.
API for :checked Selector
To get the value of the selected radio that uses a class:
$('.class:checked').val()
I use this simple script
$('input[name="myRadio"]').on('change', function() {
var radioValue = $('input[name="myRadio"]:checked').val();
alert(radioValue);
});
Use this:
value = $('input[name=button-name]:checked').val();
DEMO : https://jsfiddle.net/ipsjolly/xygr065w/
$(function(){
$("#submit").click(function(){
alert($('input:radio:checked').val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Sales Promotion</td>
<td><input type="radio" name="q12_3" value="1">1</td>
<td><input type="radio" name="q12_3" value="2">2</td>
<td><input type="radio" name="q12_3" value="3">3</td>
<td><input type="radio" name="q12_3" value="4">4</td>
<td><input type="radio" name="q12_3" value="5">5</td>
</tr>
</table>
<button id="submit">submit</button>
If you only have 1 set of radio buttons on 1 form, the jQuery code is as simple as this:
$( "input:checked" ).val()
I've released a library to help with this. Pulls all possible input values, actually, but also includes which radio button was checked. You can check it out at https://github.com/mazondo/formalizedata
It'll give you a js object of the answers, so a form like:
<form>
<input type="radio" name"favorite-color" value="blue" checked> Blue
<input type="radio" name="favorite-color" value="red"> Red
</form>
will give you:
$("form").formalizeData()
{
"favorite-color" : "blue"
}
JQuery to get all the radio buttons in the form and the checked value.
$.each($("input[type='radio']").filter(":checked"), function () {
console.log("Name:" + this.name);
console.log("Value:" + $(this).val());
});
To retrieve all radio buttons values in JavaScript array use following jQuery code :
var values = jQuery('input:checkbox:checked.group1').map(function () {
return this.value;
}).get();
try it-
var radioVal = $("#myform").find("input[type='radio']:checked").val();
console.log(radioVal);
Another way to get it:
$("#myForm input[type=radio]").on("change",function(){
if(this.checked) {
alert(this.value);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<span><input type="radio" name="q12_3" value="1">1</span><br>
<span><input type="radio" name="q12_3" value="2">2</span>
</form>
From this question, I came up with an alternate way to access the currently selected input when you're within a click event for its respective label. The reason why is because the newly selected input isn't updated until after its label's click event.
TL;DR
$('label').click(function() {
var selected = $('#' + $(this).attr('for')).val();
...
});
$(function() {
// this outright does not work properly as explained above
$('#reported label').click(function() {
var query = $('input[name="filter"]:checked').val();
var time = (new Date()).toString();
$('.query[data-method="click event"]').html(query + ' at ' + time);
});
// this works, but fails to update when same label is clicked consecutively
$('#reported input[name="filter"]').on('change', function() {
var query = $('input[name="filter"]:checked').val();
var time = (new Date()).toString();
$('.query[data-method="change event"]').html(query + ' at ' + time);
});
// here is the solution I came up with
$('#reported label').click(function() {
var query = $('#' + $(this).attr('for')).val();
var time = (new Date()).toString();
$('.query[data-method="click event with this"]').html(query + ' at ' + time);
});
});
input[name="filter"] {
display: none;
}
#reported label {
background-color: #ccc;
padding: 5px;
margin: 5px;
border-radius: 5px;
cursor: pointer;
}
.query {
padding: 5px;
margin: 5px;
}
.query:before {
content: "on " attr(data-method)": ";
}
[data-method="click event"] {
color: red;
}
[data-method="change event"] {
color: #cc0;
}
[data-method="click event with this"] {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="reported">
<input type="radio" name="filter" id="question" value="questions" checked="checked">
<label for="question">Questions</label>
<input type="radio" name="filter" id="answer" value="answers">
<label for="answer">Answers</label>
<input type="radio" name="filter" id="comment" value="comments">
<label for="comment">Comments</label>
<input type="radio" name="filter" id="user" value="users">
<label for="user">Users</label>
<input type="radio" name="filter" id="company" value="companies">
<label for="company">Companies</label>
<div class="query" data-method="click event"></div>
<div class="query" data-method="change event"></div>
<div class="query" data-method="click event with this"></div>
</form>
$(function () {
// Someone has clicked one of the radio buttons
var myform= 'form.myform';
$(myform).click(function () {
var radValue= "";
$(this).find('input[type=radio]:checked').each(function () {
radValue= $(this).val();
});
})
});

Categories

Resources