Cloning forms with radio buttons - javascript

Cloning forms in jQuery, for example to create an RSVP option on a guest list with multiple people, is relatively simple.
$(selector).clone().insertAfter(selector:last)
It's relatively easy with inputs as well, offering the ability to copy methods or properties by passing true to the clone() method. To cope with multiple inputs you can append [] to the end of your input names:
<input type="text" name="email_address[]"/>
However this becomes more complicated with <input> elements of type radio, as you would usually use these to denote a choice:
<input type="radio" name="choice" value="1"/> <input type="radio" name="choice" value="2"/>
Adding the square bracket syntax further confuses things, as there are still multiple values, and some browsers may now allow different selections:
<label>Person:</label> <input type="radio" name="choice[]" value="1"/> <input type="radio" name="choice[]" value="2"/>
<label>Person:</label> <input type="radio" name="choice[]" value="1"/> <input type="radio" name="choice[]" value="2"/>
How can we solve this in a way which allows easy cloning whilst not making radio buttons hard to parse on the back end?

Turns out this can be achieved with a little bit of RegEx fun!
Firstly add a numeric value to your first input element:
<input type="radio" name="choice[0]" value="1"> <input type="radio" name="choice[0]" value="2">
Now in your JavaScript
$(selector).clone().insertAfter(selector:last)
.find('input[type="radio"]').each(function(){
var name=$(this).attr('name');
$(this).attr('name',name.replace(/([0-9]+)/g,1*(name.match(/([0-9]+)/g))+1));
});
Which creates a simple increment in numbers for each element in line with their siblings.

Related

Getting the value of a checked radio button using javascript [duplicate]

This question already has answers here:
How to get the selected radio button’s value?
(19 answers)
Closed 5 years ago.
I am trying to access the value of a checked radio button in my form using JavaScript only, no jQuery. I have looked this up and seen many answers but when I copy the same code into my project it doesn't work for some reason. Here is my code.
<form>
<input type="radio" name="style" value="3" checked>
<input type="radio" name="style" value="5">
<input type="radio" name="style" value="10">
</form>
I tried to access the value using this JavaScript code:
var value = document.querySelector('input[name="style"]:checked').value;
console.log(value);
I would assume this would give me the string of 3 as the logged value. When I try this example I get the following error:
request.js:1 Uncaught TypeError: Cannot read property 'value' of null
at request.js:1
I also tried using a for loop of an array of the inputs named style and that didn't work either. It found all three inputs but didn't have values for them in the array. Can someone please explain what is wrong? And if this is obvious please be patient I am still learning I am just trying to get better.
Your code is correct, you only need is an event to run the selector code to get the value of selected value. See below code :- you can also use javascript selector for click event instead of function placement in onclick event handler.
function run_test(){
var radio_ele = document.querySelector('input[name="style"]:checked');
console.log(radio_ele.value);
}
<form>
<input type="radio" name="style" value="3">
<input type="radio" name="style" value="5">
<input type="radio" name="style" value="10">
<button type="button" onclick="run_test()">click</button>
</form>
function getValue() {
var value = document.querySelector('input[name="style"]:checked').value;
console.log(value);
}
<form>
<input type="radio" name="style" value="3" checked>
<input type="radio" name="style" value="5">
<input type="radio" name="style" value="10">
<button type="button" onclick="getValue()">click</button>
</form>
you code is working fine, except you need event to get latest value after load

Jquery steps "destroy" method is removing values given by User

I have a Questionnaire form which is break down in steps by using JQuery steps plugin. In the process of form submission there is a certain point where i need to remove steps. When i use "destroy" JQuery steps method, the values filled in the form are lost.
For example:
<form>
<h3>Form A</h3>
<section>
What is your name?<br/>
<input type="text" value="" name="yourname" />
What is your age group? <br/>
<input type="radio" name="agegroup" value="1" />1-20
<input type="radio" name="agegroup" value="2" />20-40
<input type="radio" name="agegroup" value="3" />40-60
<input type="radio" name="agegroup" value="4" />60+
......
......
<section>
</form>
I am using following steps:
Convert form into Jquery steps
Opening this form in Simple modal dialog.
User fill this form and close modal dialog.
I am using "destroy" jQuery steps method after closing dialog.
When user re-open simple modal dialog again then i am converting this form into JQuery steps. At that point user see that all filled values in the form are lost.
The problem is at the 4th step. User have filled form at 3rd step. When i converted in back to original HTML, values given by user are lost.
Expected values at 4th step
<h3>Form A</h3>
<section>
What is your name?<br/>
<input type="text" value="Ishwar Lal" name="yourname" />
What is your age group? <br/>
<input type="radio" name="agegroup" value="1" />1-20
<input type="radio" name="agegroup" value="2" selected='selected' />20-40
<input type="radio" name="agegroup" value="3" />40-60
<input type="radio" name="agegroup" value="4" />60+
......
......
<section>
but output is:
<h3>Form A</h3>
<section>
What is your name?<br/>
<input type="text" value="" name="yourname" />
What is your age group? <br/>
<input type="radio" name="agegroup" value="1" />1-20
<input type="radio" name="agegroup" value="2" />20-40
<input type="radio" name="agegroup" value="3" />40-60
<input type="radio" name="agegroup" value="4" />60+
......
......
<section>
I need to remove JQuery steps from from with filled values. I have read JQuery documentation but not found any idea about this.
I think that you must to store data before you destroy the component. When you destroy a component it is destroyed, nothing else what to do.
If you store the data , then destroy object, and then initialize object with the data you stored. You can store in an array/object/variable, or you can store in sessionStorage / localStorage for use in other pages.

clicking on custom checkbox does not run the associated onClick function

I'm trying to use Ryan Fait's custom checkboxes. These are much more readable than the standard checkboxes, but clicking on them does not run the associated onClick functions. Any advice will be appreciated. The relevant portion of my code follows:
<p style="font-family:arial; font-size:large">
<input type="checkbox" class="styled" id="level-0" type="radio" value="0"
onClick="count();"> 0 (ages 5-7)
<input type="checkbox" class="styled" id="level-1" type="radio" value="1"
onClick="count();" checked> 1 (beginner)
<input type="checkbox" class="styled" id="level-2" type="radio" value="2"
onClick="count();" checked> 2 (easy)
<input type="checkbox" class="styled" id="level-3" type="radio" value="3"
onClick="count();" checked> 3 (intermediate)
<input type="checkbox" class="styled" id="level-4" type="radio" value="4"
onClick="count();"> 4 (challenging)
<input type="checkbox" class="styled" id="level-5" type="radio" value="5"
onClick="count();"> 5 (hard)
<input type="checkbox" class="styled" id="level-all" type="radio" value="6"
onClick="all_levels();"> All
<input id="available" type="button" style="background-color:white; border:2px;
font-family:arial; font-size:large" value="??"> </p> <br>
From Styling Checkboxes and Radio Buttons With CSS and JavaScript on Ryan Fait's site:
How does it work?
In a nutshell, the JavaScript looks for every form element with
class="styled" on it; hides the real form element; sticks a span tag
with a CSS class on it next to the element; and, finally, mouse events
are added to the span that handles the visual stages form inputs go
through when they are clicked.
Your inline onClick handlers are not firing because your checkboxes aren't actually being clicked. Ryan explicitly says that it "hides the real form element; sticks a span tag with a CSS class" ... so you are actually clicking on the <span> that Ryan's code inserted; the real checkbox is hidden.
Later in the article, Ryan says outright:
onChange and other JavaScript events
This script utilizes JavaScript's onChange and other events. Because
these events can only be used once, if you want to add more functions
to an event, you will need to call them from inside my script.
You will need to call them from inside my script
Take your onClick= out of the <input> tags; add your code to his code -- you'll have to figure out which bit of your code to call from his code, since I see you're doing different things from your onClicks.
You should also take your style="..." out of your tags and use a stylesheet, but that's a separate issue.

Dynamically change input id with value - input type=range

I'm making a phone gap query mobile iOS app for course evaluation at my uni. This app primary function will be a form that in it's original form uses radio buttons where each value also has a corresponding id - e.g.
<input name="q10" id="1" value="1" type="radio" />
<input name="q10" id="2" value="2" type="radio" />
<input name="q10" id="3" value="3" type="radio" />
<input name="q10" id="4" value="4" type="radio" />
<input name="q10" id="5" value="5" type="radio" />
<input name="q10" id="6" value="6" type="radio" />
But radio buttions aren't that intuitive on iOS devices so I'm using input type range instead.
This works great for changing the value between 1 and 6 but the problem is that one only specifies one id for the whole input, not one id per value.
<input type="range" name="q10" id="q10" value="0" min="0" max="6" />
Is there a way to change the id with the value? I think this should be doable through JavaScript but I lack the know-how. I also cannot change the way the database is set up (requiring both id and value) as this database belongs to the university's IT-department.
You can use the change event
<input type="range" onchange="this.id=this.value" name="q10" id="q10" value="0" min="0" max="6" />
Working example here - http://jsfiddle.net/aVHm8/
Note: I always feel uneasy about changing the ID of a DOM element .. perhaps you should investigate better options to resolve your issue
The database can't know what the id is unless you use JavaScript to send it to the server (standard form submission sends the name and the value). In which case find the bit of JS that pulls out the ID and just send the value twice instead.

Custom graphical Radio buttons with jQuery is somehow breaking index()

I'm using this customInput plugin (with jQuery 1.6.2) to customize the look of my radio buttons.
It works great.
The problem I have now is that I'm just trying to get the index() number of the selected radio button and it always returns 0. There are six radio buttons and I'm looking for a number between 0 and 5.
JavaScript:
$('input[name="amount"]').click(function() {
var x = $(this).filter(':checked').index();
var y = $(this).filter(':checked').val(); //<-- for troubleshooting
alert(x + y); //<-- for troubleshooting
});
Oddly, val() is still working fine and returns the proper value. Therefore, the form data is always getting the correct radio value.
http://jsfiddle.net/sparky672/LdVGD/
HTML:
<fieldset id="radioset">
<input type="radio" id="radio-1" name="amount" value="Option 1" checked="checked" /><label for="radio-1" title="">Option 1</label>
<input type="radio" id="radio-2" name="amount" value="Option 2" /><label for="radio-2" title="">Option 2</label>
<input type="radio" id="radio-3" name="amount" value="Option 3" /><label for="radio-3" title="">Option 3</label>
<input type="radio" id="radio-4" name="amount" value="Option 4" /><label for="radio-4" title="">Option 4</label>
<input type="radio" id="radio-5" name="amount" value="Option 5" /><label for="radio-5" title="">Option 5</label>
<input type="radio" id="radio-6" name="amount" value="Option 6" /><label for="radio-6" title="">Option 6</label>
</fieldset>
When simply not using the customInput plugin, the index number is then returned.
http://jsfiddle.net/sparky672/LdVGD/1/
Side Question:
After disabling the plugin, the index() returns 0, 2, 4, 6, 8, or 10. It's like the <label> itself is being counted at part of the index(), effectively doubling the count. Why should this be?
I cannot remove the <label> elements as the plugin depends on these to function.
I just want to retrieve a number from 0 to 5 depending on whether radio button 0 through 5 is checked.
Any suggestions? Perhaps another method to check which radio button is selected?
My ultimate goal? To simply change some variables depending on which button is selected.
As you've noticed, your index call doesn't quite work the way you expect it to when you don't use the plugin. From the fine manual:
If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.
You're getting values twice as large as you think they should be because the <label> elements are also siblings so you have five <input> elements and five <label> elements in the sibling list.
When you activate the plugin, your radio buttons get wrapped in a <div> so the structure of each button looks like this:
<div>
<input type="radio">
<label>
</div>
That leaves the radio button with a single sibling, <label>, and an index of zero.
You already have id attributes on your radio buttons so why not use those to figure out the index? Something like this:
var index = parseInt(this.id.replace(/radio-/, ''), 10) - 1;
Check the third number in these demos:
With plugin: http://jsfiddle.net/ambiguous/nGVkC/
Without plugin: http://jsfiddle.net/ambiguous/UkPh8/
Or you could use the element form of index:
If .index() is called on a collection of elements and a DOM element or jQuery object is passed in, .index() returns an integer indicating the position of the passed element relative to the original collection.
So you could do it like this:
var i = $('input[name=amount]').index(this);
And some demos:
With plugin: http://jsfiddle.net/ambiguous/yAVHn/
Without plugin: http://jsfiddle.net/ambiguous/vP3Du/

Categories