Radio option on view that updates and changes view? - javascript

I think that my problem isn't very hard -but I'm pretty new to this and having issues finding an easy solution.
I have a form that collects a few items, and an output page that creates a table based on those few items. For example, one of the form options is "Which leg is affected?" And you must choose either "Left, Right, Both".
I would like to create a radio selection option on the view so that the person using this tool won't have to click the back button to update this one field. The table that is built changes based on this one selection, so it would be nice to see those changes without resubmitting the form.
If anyone can point me in the right direction - either JavaScript or some method that involves re-sending the form values from the view - I would be very grateful.

I believe what you're describing is exactly what the idea of "single page app" style coding with Javascript is for - modifying the page with logic without necessarily needing to make a server request. I.e., you want to make an "application." Albeit a simple one.
What I recommend you look into is "event handlers," specifically the click handler.
So, if you had html that looked like: (stolen from MDN's radio page)
<form id="radio_form">
<p>Please select your preferred contact method:</p>
<div>
<input type="radio" id="contactChoice1"
name="contact" value="email">
<label for="contactChoice1">Email</label>
<input type="radio" id="contactChoice2"
name="contact" value="phone">
<label for="contactChoice2">Phone</label>
<input type="radio" id="contactChoice3"
name="contact" value="mail">
<label for="contactChoice3">Mail</label>
</div>
</form>
You could then have code that looked like
var radio = document.getElementById('radio_form');
radio.onclick = changeTable;
function changeTable(e){
// Do logic here to change table
}
The idea is your page is "waiting" for the form to be "clicked" (you could also look into onChange), and when it is clicked, a function is invoked that does further logic.
See here to figure out how to get the value of a selected radio.
See here for using javascript to insert a row into a table (what you may want to do in your changeTable function).
EDIT: One "gotcha" to look out for is if your script is running when the page is actually loaded. This can be a problem if your page loads asynchronously (doubtful). Just in case, also look into some kind of document.ready implementation: Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it

You can add an event listener for 'click' to each radio input and have the callback function modify the view in whatever way you want.
Here's an example:
const form = document.querySelector('.choice-form');
const display = document.querySelector('.display');
form.querySelectorAll('input[type="radio"]').forEach(input => {
input.addEventListener('click', () => {
display.innerHTML = "";
if (input.id === '1') {
display.innerHTML = "<span>You selected: <span class='red'>One</span></span>";
} else if (input.id === '2') {
display.innerHTML = "<span>You selected: <span class='blue'>Two</span></span>";
}
});
});
.red {
color: red;
}
.blue {
color: blue;
}
<div>
<form class='choice-form'>
<label for='choice'>Make a choice</label>
<input type='radio' id='1' name='choice'/>
<label for='1'>One</label>
<input type='radio' id='2' name='choice'/>
<label for='2'>Two</label>
</form>
<div class='display'>
</div>
</div>

Related

User input list using HTML plus a way to process the information

I am trying to run a simple code for something at work -- me and my co-workers are going to make a list of songs. So using what seems to be a pretty simple coding in HTML I managed to achieve the following:
<!DOCTYPE html>
<html>
<body>
<form action="list">
Band Name:<br>
<input type="text" name="BandName">
<br>
Song Name:<br>
<input type="text" name="SongName">
<br><br>
<input type="submit">
</form>
</body>
</html>
This runs fine to create the buttons and boxes for user input. But I still do not know how to process this information. The ideal result would be a way to append the names, as the users placed their inputs, in a list at the action page. Would that be possible? I'm trying to achieve this in the HTML box of google sites, by the way.
Edit:
With some help, I was able to run the following code on http://jsfiddle.net/:
////HTML///
<form>
Band/Artist:<br>
<input type='text' id='idea' />
<br>
Music:<br>
<input type='text' id='idea2' />
<br><br>
<input type='button' value='Adicione' id='add' />
<ul id='list'></ul>
<script type="text/javascript">
////JAVASCRIPT//////
//Defining a listener for our button, specifically, an onclick handler
document.getElementById("add").onclick = function() {
//First things first, we need our text:
var text = document.getElementById("idea").value; //.value gets input value
var text2 = document.getElementById("idea2").value; //.value gets input value
//Now construct a quick list element
var node = document.createElement("li");
var textnode = document.createTextNode(text+" - "+text2);
node.appendChild(textnode);
//Now use appendChild and add it to the list!
document.getElementById("list").appendChild(node);
(the code came partially from TymeVM's answer in adding user input to a list of text items on a html page, but something seemed to be wrong with it)
It works fine. But I was not able to run it on page of Google Sites. Is it possible? If not, do you guys know a better option?
As my edition seems to answer my question, I'll post it also as an answer. Please feel free to add any suggestions to it.
The following code, with the addition of Javascript, produces the needed answer for the first question above, according to http://jsfiddle.net/.
////HTML///
<form>
Band/Artist:<br>
<input type='text' id='idea' />
<br>
Music:<br>
<input type='text' id='idea2' />
<br><br>
<input type='button' value='Adicione' id='add' />
<ul id='list'></ul>
<script type="text/javascript">
////JAVASCRIPT//////
//Defining a listener for our button, specifically, an onclick handler
document.getElementById("add").onclick = function() {
//First things first, we need our text:
var text = document.getElementById("idea").value; //.value gets input value
var text2 = document.getElementById("idea2").value; //.value gets input value
//Now construct a quick list element
var node = document.createElement("li");
var textnode = document.createTextNode(text+" - "+text2);
node.appendChild(textnode);
//Now use appendChild and add it to the list!
document.getElementById("list").appendChild(node);
(As it was pointed in the edition of the question above, the code came partially from TymeVM's answer in adding user input to a list of text items on a html page. But it did not work on http://jsfiddle.net/)
But still does not run on Google Sites, it seems. I do not know if I should create another question for this problem.

Chrome Auto-checked radio button, hidden div with "required" blocking POST

EDIT 3: Ahha... some progress. The problem was actually in some code below the divs that I left out (updated HTML below to reflect). The second div contains a "required" input, so simply changing the div to display=none via javascript doesn't actually make the page entirely ignore the hidden Div. So a slight change to the angle of my question - how would I adjust the code below to completely ignore the hidden div, so that the required field is not read?
EDIT 2:I have tried removing the 2nd block of JS code below and inserting the dynamic PHP code directly into the input and div tags to change the display - still no luck.
EDIT 1: Just to confirm, the solution to a similar question doesn't work in this case: Auto checked radio buttons and php form processing - How to avoid blank field? it seems that the Chrome team have made changes in later versions that make this solution redundant.
A user on the website can select either Points or Stamps - I get the value from the Database via PHP and the form should have the relevant radio button checked and only show the Div related to that radio button.
Everything works fine, however, unless I manually change the radio button it will not let me POST the form i.e. I cannot post with value selected automatically from the DB - it seems a similar problem to this (Chrome Browser Ignoring AutoComplete=Off) - but no matter what I do with Chrome autocomplete it doesn't work. Also the page is recognising the radio as checked because it shows my dot in the right place. (EDIT 3: still unsure why this works in Mozilla but not Chrome - but latest Edits make this less important)
Heres my JS that shows the right Div if a radio button is changed:
$(function () {
var $divs = $('#option > div');
$('input[type=radio]').change(function() {
$divs.hide();
$divs.eq( $('input[type=radio]').index( this ) ).show();
});
});
This JS sets the correct radio button based on DB and shows the correct div when the page loads:
$(function() {
var $radios = $('input:radio[name=selection]');
var $type = "<?php echo $type; ?>";
if($type === 'points') {
$radios.filter('[value=points]').prop('checked', true);
document.getElementById('pointsdiv').style.display = 'block';
document.getElementById('stampdiv').style.display = 'none';
}
else if($type === 'stamp') {
$radios.filter('[value=stamp]').prop('checked', true);
document.getElementById('stampdiv').style.display = 'block';
document.getElementById('pointsdiv').style.display = 'none';
}
});
My HTML and PHP:
$type = $_SESSION['user']['type']; //Note: This is actually set at the very top of the page i.e. before the JS
<form autocomplete="off" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST" role="form">
<input type="radio" id="selection" name="selection" value="points"></input><label>Points</label>
<input type="radio" id="selection" name="selection" value="stamp"></input><label>Stamps</label><br></br>
<div id="option">
<div id="pointsdiv">
//Points related information here
<input type="text" required="required"/>
</div>
<div id="stampdiv">
//Stamp related information here - below input is required so when pointsdiv is displayed, this entire div should not even load
<input type="text" required="required"/>
</div>
</div>
<button type="submit" class="button">Save</button>
</form>
Anyone have any ideas how I can load this page and post the form if I don't change the radio button - i.e. if it loads with "Points" checked and I click the Save button?
Input radio groups must have the same name but not the same id,
so you should change id="selection" for one of them.
If everything is in the same page and the page is in php,
then you have to wait for dom ready before setting input values.
There is a dynamic way without using javascript :
<input type="radio" <?=$type =='points'?='checked="checked"':''?> id="selection" name="selection" value="points">
The same thing you can do with the other radiobutton
and also with the divs pointsdiv and stampdivs

Can’t Make Only One .children( ) Show Up When Using the onkeyup Event

Long time reader, first time poster. I’ve tried looking for an answer everywhere. I’m really stuck.
I have a form with two label tags, each containing an input and a select tag:
<body>
<form action="Page_Form.php" method="post">
<label class="try">Main Product: <input type="text" autocomplete="off" name="main_product" id="main_product" maxlength="30" onkeyup="getNames(this.value)"/>
<select multiple="multiple" class="results" id="results" onchange="displayResult(this)"><option></option></select></label>
<label class="try">Secondary Product: <input type="text" autocomplete="off" name="secondary_product" id="secondary_product" maxlength="30" onkeyup="getNames(this.value)"/>
<select multiple="multiple" class="results" id="results" onchange="displayResult(this)"><option></option></select>
</label>
</form>
</body>
When the user writes something, the tag with the class ".results" shows up, using the onkeyup event. Here's my JavaScript:
<script type="text/javascript">
function getNames(value) {
if(value != "") {$("label").children(".results",$(this)).show();} else {$("label").children(".results",$(this)).hide();}
}
function resultsHide() {
{$(".results").hide();};
}
window.onload = resultsHide;
</script>
The problem is, both of the select tags show up simultaneously, and I want only the direct child select tag of the label tag to show up.
I’ve tried using .children() and. find (), in any variation I could think of.
Is there a way to make only the direct child show up?
Here is a Live Demo.
Thank you so much for helping me out.
First remove the onkeypress attributes from the elements and do the binding through jquery, so this will actually point to the element.
also add a common class to the elements you want to have the same behavior (i used class products), like this
<input type="text" class="product" autocomplete="off" name="main_product" id="main_product" maxlength="30"/>
Try this code instead
$(function(){
$('.product').on('keyup', getNames);
});
function getNames() {
var value = this.value,
results = $(this).siblings('.results');
if (value != "") {
results.show();
} else {
results.hide();
}
}
The idea is to start traversing the DOM from the element you already have (the input in this case) towards the element you want (since they are related)
Demo at http://jsfiddle.net/gaby/xNu53/25/
You need to distinguish between the two selects when showing/hiding.
Something like this:
if($(product).hasClass("main")) {
$("label").children(".results.main",$(this)).show();
}
else {$("label").children(".results.main",$(this)).hide();}
Take a look at this modified version.
http://jsfiddle.net/xNu53/33/

Protect unspecified Javascript event handlers from being garbage collected

Recently I posed a question, asking why some of my javascript code was misbehaving. However, the accepted answer didn't fully solve my problem, so here I am once again.
Problem Description
I have a <div> which has a collection of radio buttons in it.
I use jquery ui to style that collection with a buttonset(). It looks resonably pretty.
Then I empty the <div> with jquery by doing something to the effect of $("#mydiv").html("")
Then I once again restore exact contents that were removed.
Finally the buttonset is no longer working properly, because its events got unhinged in the process.
So my question is how to protect such bound events from being garbage collected, when I temporarily tinker with the DOM?
NB! I can't do display:none to hide the <div> instead, because the whole business with deleting html content and restoring it later is handled by an unnamed jquery plugin. Nor can I call buttonset() again, because a) the graphic style gets messed up, and b) there are other controls in my real problem that don't have this handy functionality. So what I really need is some way to protect all those handlers while the elements which behavior they are supposed to govern are temporarily missing from the DOM.
Sample Code
HTML
<div id="container">
<div id="buttonset">
<input type="radio" id="radio1" name="option" />
<label for="radio1">X</label>
<input type="radio" id="radio2" name="option" />
<label for="radio2">Y</label>
<input type="radio" id="radio3" name="option" />
<label for="radio3">Z</label>
</div>
</div>
<div id="control">
<input id="toggle" type="checkbox"/>
<label for="toggle">Toggle</label>
</div>
Javascript
$(function(){
$("#buttonset").buttonset();
$("#toggle").click(
function(){
if($(this).is(":checked"))
{
backup = $("#container").html();
$("#container").html("");
} else $("#container").html(backup);
}
)
});
Playable Version
See this jsFiddle
Solution
I used the idea in the accepted answer to save html contents before applying buttonset(), then reapply buttonset() each time as needed on that saved data.
Update:
Here's an updated fiddle that's pretty close to what your OP is. The basic idea is it destroys the buttonset to get the original html back
$(function() {
//Turn the radio buttons into a jquery ui buttonset
$("#buttonset").buttonset();
//Use the toggle button to hide/show the #container div.
//NB! It's not possible to do css display:none instead,
//due to some other limitations, to wit, I'm using a
//library that I can not modify.
$("#toggle").button();
var backup; // added this to prevent it from leaking onto global scope.
$("#toggle").click(function() {
if ($(this).is(":checked")) {
// restore the html back
$("#buttonset").buttonset("destroy");
backup = $("#container").html();
$("#container").html("");
}
else {
$("#container").html(backup);
$("#buttonset").buttonset();
}
})
});

jQuery/JavaScript - Hide / Show Drop down box pending on Radio Button

I want to make it so that the drop-down is only displayed when the radio button (option 3) is clicked and have it hidden if either 1 or 2 is selected. What would be the best way to complete this? I have a little bit of experience with JavaScript and slim to none with jQuery but it seemed like it might be the way to go.
Thanks for any help,
Dan
Here is the HTML code I have as of now:
<p class="help">Selection:</p>
<div id='buttons'>
<label><input type="radio" name="select" /> Option 1 </label>
<label><input type="radio" name="select" /> Option 2</label>
<label><input type="radio" name="select" /> Option 3</label>
</div>
<div id="list" style="display: none;">
<label>Please Select From the List:
<select>
<option>True</option>
<option>False</option>
</select>
</label>
</div>
$(document).ready(function(){
$("[name=select]").change(function(){ // Whenever the radio buttons change
$("#list").toggle($("[name=select]").index(this)===2); // Only keep the list open when it's the last option (First option = 0, Third option = 2)
});
});
This code in action.
Assuming you are using jquery, as it sounds like it from your question, you could modify your HTML like so:
<p class="help">Selection:</p>
<div id='buttons'>
<label><input type="radio" name="select" id="option1" /> Option 1 </label>
<label><input type="radio" name="select" id="option2" /> Option 2</label>
<label><input type="radio" name="select" id="option3" /> Option 3</label>
</div>
<div id="list">
<label>Please Select From the List:
<select id="mySelect">
<option>True</option>
<option>False</option>
</select>
</label>
</div>​
</p>
Then you could write some jquery like so:
$(document).ready(
function()
{
$("#option1, #option2, #option3").click(
function()
{
if (this.id == "option3")
$("#mySelect").hide();
else
$("#mySelect").show();
});
});​
You can see it working here: http://jsfiddle.net/AVFuY/3/
EDIT: I removed the unneeded class and just used the id's so as to not confuse and add unnecessary code.
Since this is a fairly basic question, I think it'll be instructional to walk you through the jQuery documentation while I answer your question. If you know truly nothing about jQuery, I recommend following this short tutorial first -- it will make things much, much easier for you in the future: jQuery Documentation - Getting Started With jQuery
Your requirement is that something happens (in this case, another element is hidden/shown) when we click the radio buttons. There's two parts to this problem: first, we need to find the radio buttons, then we need to make something happen when we click it.
1. Finding the radio buttons
Take a look at the jQuery Selector documentation here: http://api.jquery.com/category/selectors/
As you can see, there's a specific pseudo-selector for radio buttons, ":radio". We want to select everything inside of the element with ID "buttons", so this is how the selector will look in total:
$("#buttons input:radio");
By the way, it's called a "pseudo-selector" because it filters items we've already selected (in this case, input tags inside of a div with id "button"). Pseudo-selectors always start with a ":".
2. Making something happen when we click them
Consult the jQuery Events reference here: http://api.jquery.com/category/events/
We want the ".click()" event here, clearly. Once we've selected our elements, we can apply a click handler to them like this:
$("#buttons input:radio").click(function() {
// make something happen here
alert("input button clicked: " + $(this).index());
});
Note that this will apply the same click handler to all three of the input buttons, but you can access the specific element that was clicked via the "this" keyword. Wrapping $() around it makes it into a jQuery selection rather than just a Javascript object and allows us to call jQuery functions on it.
3. Hiding and showing the list element conditionally
Let's extend the code above to actually hide and show that other div, depending on which item was clicked. We're going to refer to the jQuery Effects documentation so that we can make hiding and showing it exciting: http://api.jquery.com/category/effects/
The functions we'll be using are ".slideUp()", which hides an element, and ".slideDown()", which shows it. We'll also be using the ".index()" function I used in the previous example to figure out which button was clicked, although I recommend giving the button a unique ID in the future so that your code isn't dependent on the order of the buttons. Here's the final code:
$("#buttons input:radio").click(function() {
// if it was the third button (0-indexed, so the 3rd one is index 2)...
if ($(this).index() == 2) {
// display the element with ID "list"
$("#list").slideDown();
}
else {
// hide the element with ID "list"
$("#list").slideUp();
}
});
Sorry for the length of this answer, but hopefully it was more conducive to your understanding of jQuery than "copy and paste this 3-line super-compact solution".
<label><input type="radio" name="select" onclick="document.getElementById('list').style.display=this.checked?'':'none'" /> Option 3</label>
Without changing your markup:
$(function()
{
$("#list").hide();
$("#buttons input:radio[name=select]").click(function()
{
var myindex = $("#buttons input:radio[name=select]").index(this);
if (myindex == 2)
{
$("#list").show();
}
else
{
$("#list").hide();
};
});
});
EDIT: Another option: just show it on the last button in the list.
$(function()
{
$("#list").hide();
$("#buttons input:radio[name=select]").click(function()
{
var myindex = $("#buttons input:radio[name=select]").index(this);
var lastone = $("#buttons input:radio[name=select]:last").index("#buttons input:radio[name=select]");
if (myindex == lastone)
{
$("#list").show();
}
else
{
$("#list").hide();
};
});
});

Categories