RadioButton JS doesn't work with input ids - javascript

Input ids when called through JS doesn't work. What I need is to make changes to the input fields such as hide & show, set input property to "required" and remove property "required"
through ids called in JS when a radiobutton is clicked. I did put "div" referred from a source, edited some and come up with this. I have here my complete codes for my problem so I can deliver my problem understandably.
CSS & JS in the head:
<style type="text/css">
.box{
padding: 20px;
display: none;
margin-top: 20px;
border: 1px solid #000;
}
.red{ background: #ff0000; }
</style>
<script type="text/javascript">
$(document).ready(function(){
$('input[type="radio"]').click(function(){
if($(this).attr("value")=='red'){
$(".box").hide();
$(".red").show();
$('input[type="text"]').hide();
$('input[type="submit"]').hide();
}
if($(this).attr("value")=='rd1'){
var show1 = getElementById('showthis1');
var show2 = getElementById('showthis2');
$('input[type="text"]' + show1).show();
$('input[type="text"]' + show1).attr("required","required");
$('input[type="text"]' + show2).hide();
$('input[type="text"]' + show2).removeAttr("required");
$('input[type="submit"]').show();
}
if($(this).attr("value")=='rd2'){
var show1 = getElementById('showthis1');
var show2 = getElementById('showthis2');
$('input[type="text"]' + show1).hide();
$('input[type="text"]' + show1).removeAttr("required");
$('input[type="text"]' + show2).show();
$('input[type="text"]' + show2).attr("required","required");
$('input[type="submit"]').show();
}
});
});
</script>
for the body:
<from action="">
<label><input type="radio" name = 'selecthere' value="red"> red</label>
<label><input type="radio" name = 'selecthere' value="rd1"> rad1</label>
<label><input type="radio" name = 'selecthere' value="rd2"> rad2</label>
<div class="red box">You have selected <strong>red radio button</strong> so i am here</div>
<input type="text" name="here1" id="showthis1" required/>
<input type="text" name="here2" id="showthis2" required/>
<input type="submit" id="showthis" value="Click"/>
</form>
Do I need to reconstruct this one? I really need help about this. Any help may add additional idea to me in the field of page development. Thanks in advance.

1.- You have to use document.getElementById
2.- To optimize code use switch
3.- As you are getting the elements by ID and then you pass them to JQuery, you simply can pass them use this:
$("#showthis1").hide();
$("#showthis1").removeAttr("required");
instead of
var show1 = document.getElementById('showthis1');
var show2 = document.getElementById('showthis2');
$('input[type="text"]' + show1).show();
$('input[type="text"]' + show1).attr("required","required");
JSFIDDLE DEMO

Related

HTML Jquery radio buttons switch as per select

I have 2 radio buttons that switch on selected. When one of the two radio buttons is selected, there should be a description for it, when the other is selected, the description should change.
The code below does pretty much what I want, but the problem is it does it on CLICK. One of the radio buttons will come as pre-selected (with 'checked' attribute) and a description isn't going to show up until the user clicks a radio button. Thus I would like for the description to match the corresponding radio button if one of them is pre-checked.
$(document).ready(function(){
$('input[name="subscription-type"]').click(function(){
var inputValue = $(this).attr("value");
var targetBox = $("." + inputValue);
$(".subscription-desc").not(targetBox).hide();
$(targetBox).show();
});
});
.subscription-desc {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="radio-toolbar-3">
<input type="radio" id="classic" name="subscription-type" value="classic" class="choose" checked>
<label for="classic">Classic</label>
<input type="radio" id="adventurer" name="subscription-type" value="adventurer" class="choose">
<label for="adventurer">Adventurer</label>
</div>
<div class="classic subscription-desc">
Description 1
</div>
<div class="adventurer subscription-desc">
Description 2
</div>
Basically in the above, "Classic" option will come as pre-selected, but there is no description for it until the user clicks it.
Seems like a simple problem but I just can't find a solution for it. Any help appreciated. Thanks
You can trigger the .click event on the :checked radio button so that it fires the click event:
$('input[name="subscription-type"]:checked').click();
$(document).ready(function() {
$('input[name="subscription-type"]').click(function() {
var inputValue = $(this).attr("value");
var targetBox = $("." + inputValue);
$(".subscription-desc").not(targetBox).hide();
$(targetBox).show();
});
$('input[name="subscription-type"]:checked').click();
});
.subscription-desc {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="radio-toolbar-3">
<input type="radio" id="classic" name="subscription-type" value="classic" class="choose" checked>
<label for="classic">Classic</label>
<input type="radio" id="adventurer" name="subscription-type" value="adventurer" class="choose">
<label for="adventurer">Adventurer</label>
</div>
<div class="classic subscription-desc">
Description 1
</div>
<div class="adventurer subscription-desc">
Description 2
</div>
Alternatively, you can extract the code that does the display into a function and call that:
function updateSubscription() {
var inp = $('input[name="subscription-type"]:checked');
var inputValue = $(inp).attr("value");
var targetBox = $("." + inputValue);
$(".subscription-desc").not(targetBox).hide();
$(targetBox).show();
}
$(document).ready(function() {
$('input[name="subscription-type"]').click(updateSubscription);
updateSubscription();
});
function updateSubscription() {
var inp = $('input[name="subscription-type"]:checked');
var inputValue = $(inp).attr("value");
var targetBox = $("." + inputValue);
$(".subscription-desc").not(targetBox).hide();
$(targetBox).show();
}
$(document).ready(function() {
$('input[name="subscription-type"]').click(updateSubscription);
updateSubscription();
});
.subscription-desc {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="radio-toolbar-3">
<input type="radio" id="classic" name="subscription-type" value="classic" class="choose" checked>
<label for="classic">Classic</label>
<input type="radio" id="adventurer" name="subscription-type" value="adventurer" class="choose">
<label for="adventurer">Adventurer</label>
</div>
<div class="classic subscription-desc">
Description 1
</div>
<div class="adventurer subscription-desc">
Description 2
</div>
Note you can also use
var inputValue = $('input[name="subscription-type"]').val()
instead of
var inp = $('input[name="subscription-type"]:checked');
var inputValue = $(inp).attr("value");
I've kept the code above close to your original, just replacing the clicked this with $('input[name="subscription-type"]:checked')
Another alternative is to show the correct description at the time of load - this way you also don't get the "FOUC" (flash of unstyled content) where the description is displayed only after the page has fully loaded.
How you do this will depend on how you set the 'checked' value on the radio at page load, so may not be a suitable solution.

jquery, js. custom text color

How can i change the color of the text inside input box to different color. eg. text to green, red, purple etc.. I planned to use select box to store the different color and based on the selected color change the "text" color: but I am having hard time implementing into code. I am new to js, jquery any help will be greatly appreciated. Also what needs to be done to get the text with selected color to a table(do i save the color in databse?). I will be very thankful to get any help on this .
I made a small demo based on your requirements. You can read the comments in the code.
Something like this:
(function() {
function get(id) {
return document.getElementById(id); // Return the element given an id.
}
var selColors = get("selColors"); // Store the context of the selColors element.
var txtMyText = get("txtMyText"); // Store the context of the txtMyText element.
var myForm = get("myForm"); // Store the context of the myForm element.
var selectedColor = get("selectedColor");
// This is an object that has 2 properties: (color and value). These properties can hold in it string values.
var obj = {
color: "",
value: ""
};
// When you select an option.
selColors.onchange = function() {
if (this.value.length > 0) {
obj.color = this.value; // this.value contains the color that you have selected.
selectedColor.setAttribute("style", "background-color: " + obj.color);
txtMyText.setAttribute("style", "color: " + this.value); // With this you can set a style to the txtMyText textbox.
}
};
// When you submit the form.
myForm.onsubmit = function(e) {
obj.value = txtMyText.value;
console.log(obj); // Shows in the console the object with the current color and value of your textbox.
e.preventDefault();
};
})();
#myForm {
border: solid 1px #335a82;
}
#myForm fieldset {
border: solid 1px #a3c9d4;
}
#myForm fieldset div {
margin: 5px;
}
#myForm fieldset div label {
display: inline-block;
width: 120px;
}
#selectedColor {
display: inline-block;
padding: 10px;
width: 120px;
}
<form id="myForm">
<fieldset>
<legend>Configuration</legend>
<div>
<label>Colors:</label>
<select id="selColors">
<option value="">[Select a color]</option>
<option value="#5069b1">#5069b1</option>
<option value="#ff0000">#ff0000</option>
<option value="#841b72">#841b72</option>
</select>
</div>
<label>Selected color:</label>
<div id="selectedColor">
</div>
</fieldset>
<fieldset>
<legend>Preview</legend>
<div>
<label>Text:</label>
<input id="txtMyText" type="text" />
</div>
<div>
<button type="submit">Send</button>
</div>
</fieldset>
</form>
You could use js to select the class or id of the <input class=".." id="..">
Then you would be able to change the CSS attributes with js.
See the following example
<form method="post">
<input type="text" class="input1">
</form>
So your <input> class is input1. Using the following CSS code you could select a class by its name. See the example below
<script>
function myFunction() {
var x = document.getElementsByClassName("example");
}
</script>
Now by adding a CSS atribute like color to the function you could change the existing or add a new CSS rule to your <input> field.
I think you could get pretty far with this example.
Let me know if it helps!
$('#myinput').css("color","#fdd");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="test" id="myinput">
You could try this also:
$('#myinput').css('color',$('#myinput').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="#04edee" id="myinput" onkeyup="$('#myinput').css('color',$('#myinput').val());">
jQuery option to show some fun stuff:
$(function() {
$('#myColors').on('change', function() {
var picked = $(this).val();
$('#currentcolor').css("background-color", picked);
$('#results').append("<div>" + $(this).find("option:selected").text() + "|" + picked + "</div>");
});
// verbose add on click of button
$('#addHot').on('click', function() {
var valHot = '#69b4ff';
var newName = "Hot Pink Triadic Blue";
//$('#myColors').append("<option value='"+valHot+" style='color:"+nameHot+"'>"+nameHot+"</option>");
var newOpt = $("<option></option>");
newOpt.css("color:" + valHot);
newOpt.prop("value", valHot);
newOpt.text(newName);
newOpt.appendTo('#myColors');
console.log(newOpt);
});
});
<div>
<select id="myColors">
<option value="red" style="color:red">Red</option>
<option value="green" style="color:green">Green</option>
<option value="cyan" style="color:cyan">Cyan</option>
<option value="#0080ff" style="color:#0080ff">Analogous Cyan</option>
</select>
<button id="addHot" type="button">
Add Hot Pink Triadic Blue
</button>
</div>
<div>
<div id="currentcolor">
current color is background
</div>
<div id="results">
Show stuff:
</div>
</div>
What you can do create class for every color like .green .purple and just remove and add classes
$(".input1").addClass("red").removeClass("green");
and you can also add remore these classes with selected box color change

Add value in span using JavaScript

i want to add 500 using onclick function in span 1000
means onclick at check box sapn value will be 1500
JS
function add() {
if (document.Form1.checkbox1.checked == true) {
// what will code here to sum 500 in to 1000
}
}
HTML
<form name="Form1" style="color: green ; font-size: 150%" action="#">
<input type="checkbox" name="checkbox1" onclick="add()" />500
<br />
<span>1000</span>
</form>
Make sure to add an id to your span element so you can easily target it in javascript. Then target the element and change the innerHTML.
var spanToChance = document.getElementById("#spanID");
spanToChange.innerHTML = parseInt(spanToChange.innerHTML) + 500;
If you don't want to use jQuery, then the the following can be used.
function add(element) {
var form = document.getElementsByName("Form1")[0];
var val = form.getElementsByTagName('span')[0].innerHTML;
if (element.checked == true) {
form.getElementsByTagName('span')[0].innerHTML = parseInt(val) + parseInt(element.value);
} else {
form.getElementsByTagName('span')[0].innerHTML = parseInt(val) - parseInt(element.value);
}
}
<form name="Form1" style="color: green ; font-size: 150%" action="#">
<input type="checkbox" name="checkbox1" onclick="add(this)" value="500" />500
<br />
<span>1000</span>
</form>
You can use jquery to bind change event to the checkbox instead of writing inline function calls.
Use the value attribute for checkbox in-order to provide the value.
Use parseInt before adding the contents. Otherwise it will take it as string
Example code
$("[name='checkbox1']").change(function () {
var spanvalue = parseInt($("span").text().trim());
if (this.checked) {
spanvalue = spanvalue + parseInt(this.value);
} else {
spanvalue = spanvalue - parseInt(this.value);
}
$("span").text(spanvalue);
});
Fiddle
As Kushal has mentioned in their four comments, you need to add an identifying feature to the span so you know where to put the new value.
You can then use document.getElementById() (if in javaScript) or $('#id') (in jQuery) to access this element and change the text (via innerText/innerHTML in js and .text()/.html() in jQuery)
<span id="myspan"> 1000 </span>
try this code -
document.getElementById("myspan").innerHTML="1500";
for modern browser-
document.getElementById("myspan").textContent="1500";
Please try the bellow code,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#checkbox1').click(function(){
var checkboxval = parseInt($(this).val());
var spanval = parseInt($('#total').text());
if(this.checked){
$('#total').text(checkboxval + spanval);
}
});
});
</script>
<body>
<form name="Form1" style="color: green ; font-size: 150%" action = "#">
<input type="checkbox" name="checkbox1" id="checkbox1" value="500"/>500
<br/>
<span id="total">1000</span>
</form>
</body>
Let me know if you have any query
Thanks

get label for for a check input radio

I am having a radio element that I want to get the text:
<div class="fleft multiplecolumns">
<div class="rdbUniteWrapper" style="line-height:20px">
<span class="EasilyRadioWrapper EasilyControlWrapper">
<span class="EasilyRadio EasilyChecked"></span>
<input id="rdbUnite_106" name="rdbUnite" type="radio" value="106" class="formElementHidden" checked="checked" style="opacity: 0;">
</span>
<label for="rdbUnite_106" style="font-weight: bold">kg (kilogramme)</label>
</div>
I tried $('input:radio[name=radio]:checked').next().text(); but it' s not the solution...
What am I doing wrong ?
Cheers
input:radio is not the sibling of label element, its parent span is. thus you need to traverse to parent span, then to next sibling element:
$('input:radio[name=radio]:checked').parent().next().text();
I find out the solution
var labelUnite = $('label[for="' + $("input[name='rdbUnite']:checked").attr("id") + '"]').text();
thanks for your helps
try below code
$('input:radio[name=radio]:checked').parent().next().text();
I am having a radio element that I want to get the text
Since the two are nicely related by id = for, you can use an attribute value selector:
// Assuming `this` is a reference to the radio button element
var label = $('label[for="' + this.id + '"]');
Then if you want the text, use .text():
var test = label.text();
Live example:
$("input[type=radio]").on("click", function() {
alert($('label[for="' + this.id + '"]').text());
});
Click a radio button to see its label text:
<div>
<label for="r1">This is for r1</label>
<input type="radio" id="r1">
</div>
<div>
<label for="r2">This is for r2</label>
<input type="radio" id="r2">
</div>
<div>
<label for="r3">This is for r3</label>
<input type="radio" id="r3">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
More generally, a radio button element and its label are related in one of two ways:
Via id = for, as in your example
Via containment, where the label contains the input[type=radio]
If you want to handle the general case, you can do something like this:
// Assuming `this` is the radio button element
var text;
var label = null;
if (this.id) {
label = $('label[for="' + this.id + '"]');
}
if (!label || !label[0]) {
label = $(this).closest('label');
}
text = label && label.text();
Use This :-
var label = $("label[for='"+$('input:radio[name=radio]:checked').attr('id')+"']")

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