Radio buttons checked changing submit text - javascript

My site structure consists on an index.php which is styled by a css file. It then includes the following php code in a separate file:
<?php include("globals.php"); ?>
<form action="<?php echo $website.$relative_string;?>" name="subscribe" onsubmit="javascript:return checkEmail(this);" method="post">
<div id="cell8" class="titlecell2"><h3>Email:</h3></div>
<div id="cell9" class="inputcell2">
<input type="text" class="inputfield2" name="email" value="Your Email..." id="email2" maxlength="255" onfocus="this.value='';">
</div>
<div id="cell10" class="textcell3">
<input name="group" type="hidden" id="group[]" value="<?php echo $group; ?>">
<input name="subscribe" id="sub" type="radio" value="true" checked>
</span>Subscribe </p>
</div>
<div id="cell11" class="buttoncell">
<button type="submit" name="Submit2" value="Join" id="submitButton2">
<span>OK</span>
</button>
</div>
<div id="cell8" class="textcell4">
<input type="radio" name="subscribe" id="unsub" value="false">
</span>Un-Subscribe </p>
</div>
</form>
It appears on screen with no problems in the correct layout as my css style sheet. What I would like this to do is when I select the "Subscribe" radio button the submit button text "OK" changes to "Join". When I click on the Unsubscribe button text "OK" or "Join" changes to "Leave".
I tried to make some code from research:
if(document.getElementById('sub').checked) {
document.write("<span>Join</span>"
}
else if(document.getElementById('unsub').checked) {
document.write("<span>Leave</span>)
}
I think this kind of worked in that it changed to Join (replacing the OK line, but obviously didn't update on clicking unsubscribe. I guess it would update on refreshing the page if my default wasn't join. I guess I need to do some form of onclick but then I have no idea how to adjust that span ok bit.
Please help?
Many thanks Chris

Here is a solution in plain JavaScript without jQuery. It avoids the unnecessary overhead.
This should work, but I haven't had a chance to test it:
var sub = document.getElementById('sub'); // Save element to a variable, so you don't have to look for it again
var unsub = document.getElementById('unsub');
var btn = document.getElementById('submitButton2');
sub.onchange = function() //When sub changes
{
if(sub.checked) //If it's checked
{
btn.innerHTML = "<span>Join</span>"; // Set button to Join
}
else // If not..
{
btn.innerHTML = "<span>OK</span>"; // Set button to OK
}
}
unsub.onchange = function() //When unsub changes
{
if(unsub.checked) //If it's checked
{
btn.innerHTML = "<span>Leave</span>"; // Set button to Leave
}
else // If not..
{
btn.innerHTML = "<span>OK</span>"; // Set button to OK
}
}
However, you should not do it like this.
You should combine the two radio buttons into a radio group.
In that case you will listen for radio group to change, get the value of the radio group, set button text according to the value.

if you label your <span>OK</span> to something like <span id="your_id">OK</span> then added a class to your radio button like this <input class="your_class" type="radio" name="subscribe" id="unsub" value="false"> them...
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$("#your_class").change(function () {
if ($(this).is(':checked')) {
$("#your_id").text('Join');
}else {
$("#your_id").text('Leave');
}
});
</script>
This was all written in the browser so let me know if there are any problems.

Related

Add required to input of hidden div when radio is checked

What I'm trying to do is to set hidden div with inputs depended on checked radio input.
This is the logic:
If the first radio is checked the first div is shown, there I want to add hidden inputs with some values...
If the second radio is checked I want the input to be added with required..
And, it shouldn't be required if the 2nd radio isn't checked...
I've tried a few things over some time and got some effects but can't get it work as I want, Here is the code that i'm currently trying to work with, sorry but it's messed up and fails...
So Any help will be much appreciated...
/*
// this code is working but I messed the HTML while trying to get it work with the other code below...
$(document).ready(function() {
$("div.hiddendiv").hide();
check();
$("input[name$='name02']").change(check);
function check() {
var test = $("input[name$='name02']:checked").val();
$("div.hiddendiv").hide();
$("#" + test).show();
}
}
*/
// The code i'm trying to work with...
$(function() {
var radio = $("#closed");
var hidden = $("#hide");
hidden.hide();
checkbox.change(function() {
if (checkbox.is(':checked')) {
hidden.show();
//add required
$('#name02').prop('required', true);
} else {
hidden.hide();
//clear when hidden checked
$("#name02").val("");
//remove required
$('#name02').prop('required', false);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="closed" value="01"> Closed
<input type="radio" id="open" value="02"> Open
<div name="01" class="hiddendiv">
<input name="name01" type="hidden" value="code">
</div>
<div name="02" id="hide" class="hiddendiv">
<input name="name02" type="text" value="">
</div>
Here is the JSFiddle,
try this code
give same name of radio button so it will work as a group and
also set id of input tag as name02 so its use as a #name02 in jquery
so it will work
$(function() {
var radio = $("#closed");
var hidden = $("#hide");
hidden.hide();
$(this).click(function() {
if ($('#closed').is(':checked')) {
hidden.show();
$('#name02').prop('required', true);
} else {
hidden.hide();
//clear when hidden checked
$("#name02").val("");
//remove required
$('#name02').prop('required', false);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name='btn' id="closed" value="01"> Closed
<input type="radio" name='btn' id="open" value="02"> Open
<div name="01" class="hiddendiv">
<input name="name01" type="hidden" value="code">
</div>
<div name="02" id="hide" class="hiddendiv">
<input name="name02" id="name02" type="text" value="">
</div>
Part of your problem is that you need to set the name attribute of your radio buttons to be the same value, otherwise the HTML won't know that they belong to the same group.
I've updated the JSfiddle here
https://jsfiddle.net/hba4d83k/2/
What i have done is add a change event handler to your the radio group and then did some conditional logic to show/hide the relevant inputs.

javascript - How to dynamically change information displayed by radio button?

(Duplicate?) I've tried several Stackoverflow postings related to this, but I cannot get a javaScript example to work. I'd like to avoid having to use jQuery, for the time being.
I want to create the information shown by radio buttons dynamically, using javascript. In this example, I would want to write a function that displays some other values for these radio buttons 'Answer 1' and 'Answer 2'. For example, I don't actually want 'Answer 1'. Goal is for the user to click on one of the multiple choice answers, then hit submit/save to self-check their own knowledge.
I have already learned, through my more complex project code, that a submit/save button that is hard-coded into the html <form> section does not seem to associate with values displayed by the radio buttons, that I managed to add in using javaScript * It seems to me that changing hardcoded information already displayed by the radio buttons might work.
When user clicks on the submit/'save' button, I don't need to refer to the actual answer information that the radio button is displaying. I only need to know whether , in this case, it's the first or second answer chosen.
<html>
<script type="text/javascript">
function OnSubmitForm()
{
if(document.myform.operation[0].checked == true)
{
alert ( "You have selected the first answer" );
}
else
if(document.myform.operation[1].checked == true)
{
alert ( "You have selected the SECOND answer" );
}
}
</script>
<form name="myform" onsubmit="return OnSubmitForm();">
<input type="radio" name="operation" value="1" checked>Answer 1
<input type="radio" name="operation" value="2">Answer 2
<p>
<input type="submit" name="submit" value="save">
</p>
</form>
</html>
(I don't know if I should include this following example I tried as well)
BTW Here is another of the example I tried - a posting but I cannot get this idea to work . I was trying to get the first radio button to display 'junk' instead of 'Answer1' as originally hard coded. But I have an error from code borrowed from posting, that I cannot resolve.
It's from
Javascript how to change radio button label text?
<html>
<form name="myform" onsubmit="return OnSubmitForm();">
<input type="radio" id = 'first' name="operation" value="1" checked <label for="alsoFirst"> Answer 1
<input type="radio" id = 'second' name="operation" value="2"<label for="alsoSecond">Answer 2
<p>
<input type="submit" name="submit" value="save">
</p>
</form>
<script type="text/javascript">
document.addEventListener('readystatechange', function() {
// Seems like a GOOD PRACTICE - keeps me from getting type error I was getting
// https://stackoverflow.com/questions/14207922/javascript-error-null-is-not-an-object
if (document.readyState === "complete") {
init();
}
});
function init() {
console.log ("expect to change -Answer 1- displayed by first button to word junk");
// this works
var label = document.getElementById('first').getElementsByTagName('alsoFirst') [0];
// this does not work
label.innerHTML = 'junk';
}
//http://www.javascript-coder.com/html-form/html-form-action.phtml
function OnSubmitForm()
{
if(document.myform.operation[0].checked == true)
{
alert ( "You have selected the first answer" );
}
else
if(document.myform.operation[1].checked == true)
{
alert ( "You have selected the SECOND answer" );
}
if (document.uniqueName.checked == true){
alert ( "You have selected the THIRD answer" );
}
}
/*
<input type="radio" name="sex" id="male" value="male">
<label for="male">Male</label>
</input>
var input = document.getElementById('male');
var label = input.getElementsByTagName('label')[0];
label.innerHTML = 'New Text';
*/
//https://stackoverflow.com/questions/32292962/javascript-how-to-change-radio-button-label-text
</script>
</html>
I previously got values from my arrays to display by inserting table rows and concatenating strings. This worked, and went into the table, but did not tie into the submit/save button hardcoded into original <form>. I still plan to have radio answer buttons in a table, but I'm trying to make a more basic example here.
I Have made some modifications for getting label through document.getElementByTagName() and also some changes to OnSubmitForm() function. And just pasted your code with those changes below and demo link at the end.
<html>
<form name="myform" onsubmit="OnSubmitForm();">
<input type="radio" id = 'first' name="operation" value="1"
checked> <label for="alsoFirst"> Answer 1 </label>
<input type="radio" id = 'second' name="operation" value="2">
<label for="alsoSecond">Answer 2</label>
<p>
<input type="submit" name="submit" value="save">
</p>
</form>
<script type="text/javascript">
document.addEventListener('readystatechange', function() {
// Seems like a GOOD PRACTICE - keeps me from getting type error I was getting
// http://stackoverflow.com/questions/14207922/javascript-error-null-is-not-an-object
if (document.readyState === "complete") {
init();
}
});
function init() {
console.log ("expect to change -Answer 1- displayed by first button to word junk");
// this works
var label = document.getElementsByTagName('label') [0];
// this does not work
label.innerHTML = 'junk';
}
//http://www.javascript-coder.com/html-form/html-form-action.phtml
function OnSubmitForm()
{
if(document.getElementById('first').checked == true)
{
alert ( "You have selected the first answer" );
}
else
if(document.getElementById('second').checked == true)
{
alert ( "You have selected the SECOND answer" );
}
return false;
}
/*
<input type="radio" name="sex" id="male" value="male">
<label for="male">Male</label>
</input>
var input = document.getElementById('male');
var label = input.getElementsByTagName('label')[0];
label.innerHTML = 'New Text';
*/
//http://stackoverflow.com/questions/32292962/javascript-how-to-change-radio-button-label-text
</script>
</html>
Demo : https://jsbin.com/sojojiy/27/edit?html,console,output
Hope this helps. Thanks !

Javascript to enable/disable radio buttons when text field is cleared or chars are present

I'm working on a little script that will disable a form field if certain radio button are ticked or if the input filed has characters to disable the radio buttons
So what I'm wanting my code to do is when the User enters the text field and adds at least one character of any type to disable the radio buttons and if that field is cleared to re-enable the radio buttons
For some reason when I'm doing either or, my "Enabled" alert keeps showing and the radio buttons aren't being disabled
to get the alert to pop, need to click outside of the input field, I would like this to be a mouseout if possible but I can work on that later
If the value is entered within the form directly, the radio buttons are disabled but I can't get them enabled once the filed is cleared
Steps:
Enter text in text field, if value isn't set in the form. Radio buttons stay disabled
Enter Value within the form, the text buttons stay disabled when the text field is cleared
Working Parts:
If radio btn "Yes" is ticked display "test" string and disable text field
If Radio btn "No" is ticked then enable text field
jQuery version in use: 1.9
Below is my JavaScript and below that is the HTML
Script:
$(function() {
var tlHeader = 'Test';
var f2 = $('#field_2').val();
// This function controls inpput box toggling on/off radio buttons
$( '#field_2' ).change(function() {
if(f2.length != 0) {
alert( "Disabled" )
$("input[name=toggle]").prop('disabled', true)
} else if(f2.length == 0) {
alert( "Enabled" )
$("input[name=toggle]").removeProp('disabled')
};
});
window.invalidate_input = function() {
// This function controls radio btn actions
if ($('input[name=toggle]:checked').val() == "Yes") {
$('#field_2').attr('disabled', 'disabled'),
$('#thgtLdr').html( tlHeader );
$('#thgtLdr').not("No").show();
} else if ($('input[name=toggle]:checked').val() == "No") {
$('#field_2').removeAttr('disabled'),
$('#thgtLdr').not("Yes").hide();
}
};
$("input[name=toggle]").change(invalidate_input);
invalidate_input();
});
</script>
HTML:
<body>
<div id=rdTest>
<div class="inputField">
<label>Focal Image:</label>
<input name="FocalImage" type="text" id="field_2" class='textbox' value="" />
</div> <!-- End input field -->
<div class="radioGroup">
<label>Test Page:</label>
<input type='radio' name='toggle' value='Yes' id="tglyes"/>Yes
<input type='radio' name='toggle' value='No' id="tglno"/>No
</div>
<div id="thgtLdr">
</div>
</div>
</body>
Your use case isnt entirely clear but I'll show you how to achieve the basic goal.
First, I would avoid the mouse events and use keyup with a timer so that my function is only called when the user stops typing and not after each typed letter. Then it's just a mater of checking the text and acting to enable or disable the elements. Here is an example:
var keyupDelay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$('#field_2').keyup(function() {
var $this=$(this);
keyupDelay(function(){
var val=$this.val();
console.log(val);
if(val=='') $('#tglyes, #tglno').prop('disabled',true);
else $('#tglyes, #tglno').prop('disabled',false);
}, 400 ); // triggered after user stops typing for .4 seconds, adjust value as needed
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=rdTest>
<div class="inputField">
<label>Focal Image:</label>
<input name="FocalImage" type="text" id="field_2" class='textbox' value="" />
</div>
<!-- End input field -->
<div class="radioGroup">
<label>Test Page:</label>
<input type='radio' name='toggle' value='Yes' id="tglyes" disabled="true"/>Yes
<input type='radio' name='toggle' value='No' id="tglno" disabled="true"/>No
</div>
<div id="thgtLdr">
</div>
</div>
Try this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).on('click','.choice',function(){
if($(this).val() == 'yes')
{
$('.textfield').prop('disabled',true);
$('#string').html('Test Welcome');
}
else
{
$('.textfield').prop('disabled',false);
$('#string').html('');
}
});
$(document).on('keyup','.textfield',function(){
if($(this).val().length > 0)
{
$('.choice').each(function()
{
if($(this).is(':checked'))
{
$(this).attr('checked',false);
}
$(this).prop('disabled',true);
});
}
else
{
$('.choice').prop('disabled',false);
}
});
});
</script>
<body>
<form>
<input type="text" class="textfield" placeholder="enter text"/>
Yes<input type="radio" name="choice" class="choice" value="yes" />
No<input type="radio" name="choice" class="choice" value="no" />
<p id="string" ></p>
</form>
</body>
You can simplify your code in many ways.
The keyup event will be triggered every time the user releases a key on the text field. Inside the callback, you can get the value of the text field with this.value. From experience, it is best to use .prop() method when toggling certain input-related attributes like disabled and checked. You can enable/disable these attributes using booleans.
// cache the elements to avoid having retrieve the same elements many times
var $textbox = $('#field_2'),
$radios = $('input[name=toggle]'),
$div = $('#thgtLdr');
// everytime user presses a key...
$textbox.on('keyup', function() {
// check if a value was entered or not
// if so, disabled the radio buttons; otherwise enable the radio buttons
$radios.prop('disabled', this.value);
});
// when radio buttons change...
$radios.on('change', function () {
// check if value is Yes or No
if (this.value === 'Yes') {
$textbox.prop('disabled', true);
$div.text(this.value);
} else {
$textbox.prop('disabled', false);
$div.empty();
}
});
<div id=rdTest>
<div class="inputField">
<label>Focal Image:</label>
<input name="FocalImage" type="text" id="field_2" class="textbox" value="">
</div>
<div class="radioGroup">
<label>Test Page:</label>
<input type="radio" name="toggle" value="Yes" id="tglyes">Yes
<input type="radio" name="toggle" value='No' id="tglno">No
</div>
<div id="thgtLdr"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script> // place code here </script>
Also, get into the habit of caching your jQuery objects.

hide a checkbox in function another and disabled all elements to the checkbox disabled

<script type="text/javascript">
function CheckBox(checkerbox, div) {
if (checkerbox.checked) {
document.getElementById(div, Urbanoo).style.display = "block"
} else {
document.getElementById(div, Rurall).style.display = "none"
$("#Rurall").find("*").prop("disabled", true);
}
}
function CheckBox1(checkerbox1, div) {
if (checkerbox1.checked) {
document.getElementById(div, Rurall).style.display = "block"
} else {
document.getElementById(div, Urbanoo).style.display = "none"
$("#Urbanoo").find("*").prop("disabled", true);
}
}
</script>
How to hide a checkbox in function another and disabled all elements to the checkbox disabled?
<input name="Rural" type="checkbox" onclick="CheckBox1(this,'Rurall');" />
<input name="Urbano" type="checkbox" onclick="CheckBox(this,'Urbanoo');" /> Urbanoo </center>
<div id="Urbanoo" style="display:none" >
<g:render template="../DomUrbano/form"/>
</div>
The problem is that when I turn on a check box not the other box is not disabled
<div id="Rurall" style="display:none">
</br>
<g:render template="../DomRural/form"/>
</div>
I think I see what you are attempting but frankly it's less than super clear.
SO what I think you want is;
Hide other checkboxes if I check one
If I do uncheck a box, show the other one again
Show a "partner" area if I check a box
Disable other NOT partner area inputs if I check a box
I modified your markup some to make it easier and also added some additional to clearly show what is happening. I also added a data element for the partner to the input so we can make this all simpler and only have one function; now called via an event handler and NOT with inline code in markup.
Revised markup:
<span class="myinputs"><input class="mycheck" name="Rural" type="checkbox" data-partner="#Rurall" /> Rurall</span>
<span class="myinputs"><input class="mycheck" name="Urbano" type="checkbox" data-partner="#Urbanoo" /> Urbanoo</span>
<div id="Urbanoo" class="hidden others">the Urbannoo
<g:render template="../DomUrbano/form" />
<input type="textbox"/>
</div>
<div id="Rurall" class="hidden others">the Rurall
<g:render template="../DomRural/form" />
<input type="textbox"/>
</div>
Code:
$('.mycheck').on('change', function() {
var amIChecked = $(this)[0].checked;
$(this).parent().siblings('.myinputs').toggle(!amIChecked);
var pt = $(this).data('partner');// get the partner selector
$(pt).toggle(amIChecked);// show the partner in the others list
//do the enable in the partner
$('.others').filter(pt).toggle(amIChecked).find("*").prop("disabled", !amIChecked);
//do the disable in the othes list not the partner
$('.others').not(pt).find("*").prop("disabled", amIChecked);
});
Play with it all here: https://jsfiddle.net/MarkSchultheiss/cLyb103x/1/

How to make a slider bar

Aloha, I'm trying to develop a slider bar that has 3 words that you can choose from. But I'm not able to save the words as letters, all I get is number either 1,2 or 3 :(
Here's the code I have and also a picture:)
<form action="something.php" method="post" id="form">
<input type="range" min=1 max=3 step=1 name="slider">
<div id="text">
<span > Bad </span>
<span> Ok </span>
<span> Good </span>
</div>
<input type="submit" value="next" id="but"/>
</input>
</form>
So this code shows the slider bar and letters at the top (which works with my css), but when I click "Submit", on the following page (using php) I get 1, 2 or 3.
But it should be Bad, Good or Good. I'm sure that the problem is in the HTML code.
Why not just assign the numerals to values when you process the submission?
if(isset($_POST['slider'])) {
$array[1] = 'Bad';
$array[2] = 'Ok';
$array[3] = 'Good';
// This is a simplified output, but this is essentially
// the easiest way
echo $array[$_POST['slider']];
}
There is two manner to do what you want :
1 - html + javascript :
You should add a hidden input in your form which before submitting your form you give it a value among the three : Bad, OK, Good according to the value of your slider.
2 - php :
<?php
$slider_index = intval($_POST['slider']);
$word = '';
switch ($slider_index) {
case 1:
$word = 'Bad';
break;
case 2:
$word = 'OK';
break;
case 3:
$word = 'Good';
break;
}
?>
This is not possible by using html only.
You could create a hidden input field and a "change" event handler on the range input field. The event handler sets the value of the hidden input field to the label corresponding to the selected number (1: bad, 2: ok, 3: good).
Example:
<form action="something.php" method="post" id="form">
<input type="range" min=1 max=3 step=1 name="slider" id="slider">
<input type="hidden" name="sliderLabel" id="sliderLabel" />
<div id="text">
<span > Bad </span>
<span> Ok </span>
<span> Good </span>
</div>
<input type="submit" value="next" id="but" />
</form>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
(function() {
// function to update the value of the hidden field
updateSliderLabel = function() {
var selectedValue = $('#slider').val();
var selectedLabel = $('#text > span').eq(selectedValue-1).text();
$('#sliderLabel').val(selectedLabel);
}
// when slider is changed, call the update function
$('#slider').on('change', function() {
updateSliderLabel();
});
// when page is loaded, call the update function
updateSliderLabel();
})();
</script>
The advantage of this solution is, you can easily adopt your labels in the html code, you don't need to modify your php logic.

Categories