radio button default value inconsistencies - javascript

I am creating a survey. For my purposes, JS validation is fine, and I want to ensure that a radio button in each group is selected. By default, no radio buttons are selected. As I understand it, the user agent automatically sets the value to the first radio buttons value in that group.
For example:
<input type="radio" name="question_1" value="1">
<input type="radio" name="question_1" value="2">
<input type="radio" name="question_1" value="3">
Although none are pre-selected(visually) I can check the value of this group:
$('input[name="question_1"]').val();
this will return "1", the value of the first radio button. This is making it hard for me to see a "group" with no value.
Now heres where it get's weird. When I am ready to post the data to my php script, I grab it from the form like this:
$(pagesArray[currentPage]).children('form').serialize();
This grabs all of my form data nicely BUT doesn't return values for radio group that has no button checked. Why is it that I am not getting the value of the first button in the group when nothing is checked?

$('input[name="question_1"]').val();
Think about what this does. It selects all the elements that match the selector. This is all three elements. It then calls the val method, which gets the value property of the first one. (When you have multiple elements in a selection, the value of the first is returned.) Which (if any) element is checked is irrelevant: unselected elements still have a value property set.
$(pagesArray[currentPage]).children('form').serialize();
This, however, does very different logic. It looks at what fields the browser would send to the server. Since unchecked radio fields are not sent, they are not serialized.
So to quote from your question:
the user agent automatically sets the value to the first radio buttons value in that group
This is false. There is no one global input[name="question_1"] element that has a value set. There are multiple elements (none of which is selected) and you're just getting the value of the first.

To get the value of the radio button group you should use the :checked filter. Like
$('input[name="question_1"]:checked').val()
Example - jsFiddle
And serialize would only select successful controls as per the jQuery api, and a group of radio buttons with none checked is not successful
Excerpt:
Note: Only "successful controls" are serialized to the string. No
submit button value is serialized since the form was not submitted
using a button. For a form element's value to be included in the
serialized string, the element must have a name attribute. Values from
checkboxes and radio buttons (inputs of type "radio" or "checkbox")
are included only if they are checked. Data from file select elements
is not serialized.

The requirement for selecting the initial radio button in HTML 4 was never really well followed by all user agents, and was done away with in HTML5. I would manually check the first button in the list and have done with it.
http://css-tricks.com/5972-indeterminate-radio-buttons/

Related

Disable checkbox by passing the value

As the title suggests, I have a form, which as soon as the user registers he is forced to compile, then the user can return to this form, and obviously the form on the screen will present the choices that the user has previously made, now to make that the checkbox is enabled if the user has previously pressed on the checkbox, I succeed with this code here, and the checkbox, appears to me on the selected screen:
<input <?php if (!(strcmp($row_mostra_tabella_email['aut_privacy'],"S"))) {echo "checked=\"checked\"";} ?> type="checkbox" id="aut_privacy" type="checkbox" value="S" name="aut_privacy" >
the problem is that if I do the same thing with the disabled command, when the user presses enter, I don't pass the command value = "s".
I would just like the checkbox to be selected and disabled, how do I do it?
As you have discovered, when you disable the element, it is not sent to the server.
There are a couple of things you could add to the element that would prevent user interaction. One is the style property pointer-events and the other is the element attribute tabindex
If the input element has style property pointer-events: none, the user cannot access it with mouse click (or touch). WARNING: If the input has a label, the label is "clickable" too, in that case, suggest wrapping both in a <div> with that style property.
That will prevent the user from directly interacting with the element, but there is always tab. Use tabindex=-1 so that the checkbox does not "participate in sequential keyboard navigation".
Having read at Dino's answer I realise what you mean (I think). The simplest way to do that is to display the checkbox as checked and disabled then add a hidden input with the correct name and value, that way the user cannot interact with the checkbox, but the value is sent back to php in the form submission. If this isn't what you mean then you do need to re-write your question

Retrieving Preselected value in Struts 2 from Javascript

I am trying to access the value of a radio button which is already preselected in the form from Javascript but facing issue. In the form there are 2 set of radio buttons holding True and False each. Below is a rough diagram.
O T O F
O T O F
Now when the user selects the first radio button to false then second set of radio button is visible. Now the user chooses any values from the second set of radio button and navigates to first set of radio button and choose T. Now when the user clicks on false a javascript is getting called. In that I need to fetch radio button which is preselected already for the second set of radio buttons.
The preselected value I need to get it in Javascript for second set of radio button.
Code:
<s:radio id="id1" name="name1" list =${'T':'True',' F':'False'}>
<s:radio id="id2" name="name2" list =${'T':'True' 'F':'False'}>
I tried using document.getElementById("id2").value; in javascript but it doesn't give me result i.e. the preselection done in radio button for the second set, as Struts creates different id when it transforms to HTML.
How do I get the preselected value in Javascript for 2nd set of radio button ?
Utilising getElementByID() is fine as a method of retrieving the value you're after.
Struts2 shouldn't automatically be generating your HTML-DOM IDs unless you are using struts form tags, if so then their id is determine by form parameters. Else it's probably on your code for the jsp of the view(page).
Would need to see your jsp code to help, but recommend looking at the .jsp for the page to determine what ID you should look for with getElementByID()

Saving form values dependant upon onclick/onchange functions

I have a form that saves user entered values on submit with php.
Some of the fields are in div's that are display:hidden until an onclick or onchange function changes that div to show.
How can I show only the divs containing fields with saved values after the form has been submitted? I have saved the values in the always visible fields but cannot trigger their functions.
I am using very little jquery because I am new to the syntax and would prefer to implement solutions I can understand and adapt. Simple jquery is acceptable if it is a better/quicker/easier solution.
Thanks
Code Example:
<input type="radio" id="customer" name="jobtype" value="customer" onclick="getJobType()" autofocus>Customer
<input type="radio" id="store" name="jobtype" value="store" onclick="getJobType()">Store
<span id="customerjobs" style="display:none">
<select id="customer" name="customer" onchange="createJobsList(this.value)">
*various options*
</select>
<span id="jobslist"><br></span>
</span>
The first span (id=customerjobs) is initially hidden. Upon selection from the radio's, all but the corresponding span is set to display:none and the selected is set to display:block. On submit, the selected radio is saved, but the onclick isn't called to show the span.
The second span (id=jobslist) content is populated by innerHTML using the results of an ajax call to PHP when a selection is made. On submit, the selected option is saved, but the onchange isn't called to fill the span.
So I need to trigger the onclick of a saved radio value to show my content and trigger the onchange of a saved select to populate additional content.
Note: I used onblur with javascript to set the focus initially so any action would trigger the content but it caused an unnecessary pause in filling the form that I didn't want.
Page loads with only a radio selection.
User clicks radio button.
Onclick function changes style of span id=customerjobs to display:block.
The select input inside the span is now visible. The user selects an option.
Onchange function makes an ajax call to request information from the server which is placed in span id=jobslist.
User submits form to same page.
Form saves entered values so they are still selected when page reloads.
Onclick and onchange functions are not triggered by PHP saved values so steps 3 and 5 never occur. Page is left with only the radio buttons unless it is clicked again.
Well, I have a jsfiddle to illustrate my problem using default selections because I cannot use PHP to save entered values.
Imagine the form has just been submitted and the values saved are the checked radio button(customer) and the selection from the drop down(1) which adds the word "customer".
Ideally, the entire form would still be visible (The selected radio, the selected option and the content added to the last span "customer").
Instead, only the selected radio is visible unless it is clicked again to unhide the select drop down. The drop down retains its' value as well, but the content in the last span will only appear onchange.
http://jsfiddle.net/L5H2u/31/
Try it out and advance thanks for any suggestions.
Can you hook a function to onload that checks the radio buttons and simulates the click by calling getJobtype()? That will get the initial case where the radio button is already the way the user wants it. Further clicks will work as you planned.
Edited to add: If I understand you right, all is well the first time the page is loaded because the user has to click something and that runs your getJobType() function. However, when the page is reloaded, the correct radio button is already checked, the user doesn't change anything, and your function doesn't run. If that's correct, running getJobType() from onload should fix it.
You may need something like <input type="hidden" id="firstrun" value="true"> The PHP would set that to false on subsequent loads of the page, and the onload function would only make things happen if "firstrun" was false. Edit: You don't need this because getJobType() has no default action; keep reading.
Edited still more: You have checked="checked' on the Customer radio button, so if the user is a customer, even the initial run doesn't reveal the hidden material.
Remove checked="checked" when the page is initially loaded so that on the initial presentation, neither button is checked.* Then add window.onload=getJobType; to the end of your JavaScript.
On the initial load, getJobType() will do nothing since it checks both buttons and has no default action. When a button is clicked, getJobType() will run and act based on the button that was clicked.
When the page is loaded a subsequent time, one of the buttons will be checked and when onload runs getJobType() it will perform the corresponding action.
The radio buttons, SELECT values, and any other form elements that are preserved and "reflected" by the server-side PHP will be correct when the form is loaded the second (and subsequent) times. Where you need an onload JavaScript function is when one of those values also changes something else, such as making a hidden DIV visible. If there are functions other than getJobType() that manipulate the DOM, it will likely be cleaner to write an init function that sets up the DOM based on the values of the form elements as preserved by the PHP process.
* I normally advocate having some button checked by default so that the user can always get back to the initial state. This case seems to be an exception.

Checkbox value: optional or required?

According to MDN the value attribute is optional except when the value of the type attribute is radio or checkbox. But it doesn't seem to be correct. Is there anything wrong with the following:
<input type="checkbox" id="input">
<script>
document.getElementById('input').onchange = function () {
alert('Checked!');
};
</script>
DEMO
The value attribute is only required if you want the checkbox to post through a value when you submit a form. If you're not submitting a form but just want to know when it's clicked, then there's nothing wrong with your example.
Note that your example will also alert "Checked!" when the user un-checks the box too. That's why you might also want to look at the value of the checked attribute in your Javascript.
I think document says that it is mandatory to have the value when you need the selected option when posted back and to know what value is selected, i am not sure how why do you think your code should not work . In current case if you submit the form and you have to checkbox you will not come know what value is being selected.
checkbox: A check box. You must use the value attribute to define the value submitted by this item. Use the checked attribute to indicate whether this item is selected. You can also use the indeterminate attribute to indicate that the checkbox is in an indeterminate state (on most platforms, this draws a horizontal line across the checkbox).
For checkbox you may check for the 'checked' propoerty is true or false since checkbox is always used either as a flag / Boolean expression .
document.getElementById('input').onchange = function () {
alert('Checked!');
alert(document.getElementById('input').checked);
};

Selecting all checkboxes and passing it to another page on click of a button

HI,
I have multiple checkboxes in my report. I am using two buttons Select All and Deselect All for selecting all checkboxes and deselecting all checkboxes. But am not able to pass the checked values to another report. Only if I manually select the checkboxes then only those values are getting passed in the report.
Can anyone help me out with this?
I assume your select all and deselect all buttons are using javascript to set or unset all the other checkboxes in the form.
unset checkboxes are not passed on. only the set one. If you need an explicit 0 or 1 to get passed over, you will have to do something like adding extra hidden fields are are sync'ed to the state of the checkboxes, but this will be riddled with problems (eg, no javascript = FAIL).
You can have a bunch of hidden fields to accompany the checkboxes, and set their values when the checkboxes are unchecked.
Alternately, when you need two or more states for a field, use a radio button.

Categories

Resources