Jquery radio button checked value on page refresh - javascript

I have the following two radio buttons. Switching between the two values works. But after a page refresh the selected value is not there anymore. How can I handle this problem. Is there a jquery library which can handle this? Any solutions which works on each browser? Thanks for suggestions.
<input type="radio" name="lr" id="open" class="required" value="open to all" checked="checked" />
<input type="radio" name="lr" id="login_area" class="required myOption" value="login_area" />
<label for="login_area">Register</label>
<div class="login_area">...</div>
<div class="signUp_area">...</div>
$(document).ready(function() {
$('.myOption').click(function() {
var $stat = null;
$stat = $('#login_area')[0].checked;
if ($stat === true) {
$('.signUp_area').show();
$('.login_area').hide();
} else {
$('.login_area').show();
$('.signUp_area').hide();
}
});
});

JavaScript is stateless. You have to either use localStorage, cookies, or a server session to persist after a page refresh. Client side code does not do this unless stored in memory or a database.

Should you use jquery cookie.
To set:
$.cookie("var", "10");
To get:
$.cookie("var");
To delete:
$.cookie("var", null);

Related

How do I make a checkbox that automatically refreshes the page without changing the values of inputs?

I'm trying to make a checkbox that will automatically refresh the page every few seconds or minutes when checked using JavaScript.
I found some ways to make it refresh the page, but when it does that, all of the inputs including the checkbox return to their default value. I want them to keep their current value when the page gets refreshed. How can I do that?
Here's the HTML code:
<section id="menu">
<div class="menu_item">
From <input type="date" name="start_date" id="start_date"> To <input type="date" id="end_date" id="end_date">
<button id="set_dates">Set dates</button>
</div>
<div class="menu_item">
<input type="checkbox" name="auto_refresh" id="auto_refresh" checked> Auto refresh
</div>
<div class="menu_item">
<input type="checkbox" name="show_desc" id="show_desc"> Show descriptions
</div>
<div class="menu_item">
Column width <input type="number" name="col_width" id="col_width" min="100" max="5000" value="100" >
</div>
</section>
I tried using this JavaScript code but it didn't work as I expected:
let checkbox = document.getElementById("auto_refresh");
function auto_refresh() {
if(checkbox.checked == true) {
let timeoutID = setTimeout("window.location.reload()", 5000);
} else {
clearTimeout(timeoutID);
}
}
if(checkbox.checked == true) {
auto_refresh();
}
checkbox.onchange = auto_refresh;
I would appreciate some help and advice.
On every input change you can call a function and set the value to browser localStorage. Then, On page start(refresh), call a function to retrieve the data back from localStorage and set the view.
To set the value, localStorage.setItem("col_width", "100");
To retrieve the value, localStorage.getItem("col_width");

Requiring radio button selection in Javascript

I'm a total beginner to JS, trying to create a radio button with two options (left/right), in which one of the two options needs to be selected for the program to continue, or else it will display an error screen.
I've got code that will either prevent the participant from continuing no matter what they press (i.e. the error pops up regardless), or code that will allow the participant to continue no matter what (i.e. the program continues even if they don't select one of the options.) I feel like this could be something with my logical operators, but I'm really not sure. I've tried using a manual XOR and that doesn't seem to be the problem.
I'm using adapted code, so please let me know if there's anything else I can/should include!
<div class="radio"><label><input id="option1" name="option1" type="radio" value="Right" />Right</label></div>
<div class="radio"><label><input id="option1" name="option1" type="radio" value = "Left" />Left</label></div>
Code that causes the error no matter what:
<input onclick="function filledOut(id) { return (document.getElementById(id).value == 'Left')} if(filledOut('option1') ) { next(); }else{ alert('Please provide a response.'); }" type="button" value="Continue" /> </div>
</div>
Code that causes the program to continue:
<input onclick="function filledOut(id) { return ((document.getElementById(id).value == 'Left')|| (document.getElementById(id).value == 'Right'))} if(filledOut('option1') ) { next(); } else{ alert('Please provide a response.'); }" type="button" value="Continue" /> </div>
</div>
<form name="formName">
<input type="radio" name="option1" id="option1" value="Right"/>Right
<input type="radio" name="option2" id="option2" value="Left"/>Left
</form>
<input onclick="checkResponse()" type="button" value="Continue" />
checkResponse function will check if any options are selcted when user clicks on the continue button.
<script type="text/javascript">
function checkResponse(){
if (isChecked('option1') || isChecked('option2')){
next();
}else{
alert("Your error message")
}
}
function isChecked(id){
return document.getElementById(id).checked; //returns true if any options are selected
}
</script>
You need to change the ID's to something different. In the case of radio buttons, the "name" is the radio button group. You don't need the ID's unless you are going individually look at each item, and if you give them ID's, they need to be distinct from every other ID, as well as the "name" attributes.
https://www.w3schools.com/tags/att_input_type_radio.asp
<input id="optionRight" name="groupName" type="radio" value="Right" />
<input id="optionLeft" name="groupName" type="radio" value="Left" />
Also, you can make one of the radio buttons as selected by default.
How to select a radio button by default?
<input id="option1" name="groupName" type="radio" value="Right" checked="checked" />
What I've understood is that you need to show an error if nothing is checked and continue if one of them is checked.
To do that, you will need to check if either of them is checked not checking it's value & give each radio button a unique id.
You can do something similar to this
function isChecked(id){//Instead of filledOut
return document.getElementById(id).checked;
//.checked returns true or false
}
if (isChecked('option1') || isChecked('option2')){
next();
}else{
alert("Your error message")
}
Another function to get the value if you need it:
function getCheckedBtnValue(){
if(isChecked('option1')) return document.getElementById('option1').value
if(isChecked('option2')) return document.getElementById('option2').value
return null
}
//You can also use this function to check if any of them is checked
const value = getCheckedBtnValue();
if(value){
next();
}else{
alert("Your error message");
}
Also, try not to write JavaScript inside of HTML elements it can be hard to read often.
Keep JavaScripting.

Disabling a Form using Javascript under condition of "yes or no"

I have this form with Yes or No question in a radio button style to indicate whether such form has been filled out and submitted before. I want to disable this form using Javascript if the answer is "yes", per user's answer.
The "yes" would indicate that the form has already been submitted before and therefore re-filling out of the form is not allowed. This is to attempt to stop double or multiple submission.
Any advise will be greatly appreciated.
Dawn26
I might use an onchange function attached to the "Yes" radio button to either hide the form or remove it from the page altogether. Your markup might look similar to this:
<form id="formId">
<input type="radio" value="Yes" onchange="YourClass.disableForm()"/>
...
</form>
And the javascript:
var YourClass = function() {
return {
disableForm : function() {
document.getElementById("formId").setAttribute("style", "display: none;");
}
};
}();
You can create a function that disables all form controls other than the checkbox based on whether it's selected or not. This doesn't stop duplicate submission, so you will still need to handle that at the server. You can also hide the controls if you like, but just disabling them is probably sufficient.
You may also want to put up a message to explain why the form controls are disabled.
function checkDisabled(target) {
var form = target.form;
var elements = form.elements;
var disable = target.checked;
// Check every control in the form
for (var i=0, iLen=elements.length; i<iLen; i++) {
// Don't disable the checkbox
if (elements[i] != target) {
// Disable (or not) based on whether checkbox is checked
elements[i].disabled = disable;
}
}
}
Some test markup:
<label for="dateTime">Date and time<input id="dateTime" name="dateTime">
<br>
<span class="screenTip">YYYY-MM-DD hh:mm:ss</span>
</label>
<form>
Have you submitted this form before?
<input type="checkbox" name="hasBeenSubmitted" value="1" onclick="checkDisabled(this)">
<br>
Foo: <input type="text" name="foo">
<br>
Bar: <input type="text" name="bar">
<br>
<input type="submit">
</form>

Redirect browser based on radio button value

Is there an easier way to redirect the browser based on the selection from a radio button? This works but from what I'm reading on the world wide web there is probably an easier way.
This is my form:
<form>
<input type="radio" name="value" value="google"><span>Google</span><br>
<input type="radio" name="value" value="yahoo"><span>Yahoo</span><br>
<input type="radio" name="value" value="bing"><span>Bing</span>
This is my jquery:
$(function() {
$("input[name$='value']").click(function() {
var value = $(this).val();
if (value == 'google') {
window.location.assign("http://www.google.com");
}
else if (value == 'yahoo') {
window.location.assign("http://www.yahoo.com");
}
else if (value == 'bing') {
window.location.assign("http://www.bing.com");
}
});});
Thanks in advance
I would change the html just a bit to something like this:
<form>
<input type="radio" name="redirect" value="http://google.com"><span>Google</span><br>
<input type="radio" name="redirect" value="http://yahoo.com"><span>Yahoo</span><br>
<input type="radio" name="redirect" value="http://bing.com"><span>Bing</span>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$('input[type="radio"]').on('click', function() {
window.location = $(this).val();
});
</script>
I would also change to the .on() method since it simply makes a call to .on() anyways. The reason is that .click() simply makes a call to the .on() method creating one extra function call that isn't really necessary. Plus .on() is much more flexible!
LIVE DEMO
$(function() {
$("input[name$='value']").change(function() {
window.location.assign("http://www."+ this.value +".com");
});
});
window.location.replace would be the way to go if you require a http redirect. However, if you wish to maintain history(functioning browser back button) then either of window.location or window.location.href will be your best bet.
If its a single page application, then you can also consider window.location.hash for hashed url change.
To get the value of radio button, you can try
$('input[type=radio]').on('change', function(e) {
// preferred window location change appropriate as mentioned above
});
For a jquery based solution:
$('input[type=\'radio\']').on('change', function(e) {
$(location).attr('href', this.value);
});
I would set the url as the value of radio button.
<form>
<input type="radio" name="websiteRadio" value="http://www.google.com"><span>Google</span><br>
<input type="radio" name="websiteRadio" value="http://www.yahoo.com"><span>Yahoo</span><br>
<input type="radio" name="websiteRadio" value="http://www.bing.com"><span>Bing</span>
</form>
$(document).ready(function()
$("input[name='websiteRadio']").click(function() {
window.location = $(this).attr('value');
});
});

How to add dynamic data in source of html using Javascript

I am using a simple Javascript toggle function with the following code.
<script>
function add_more(){
if (document.form.more[0].checked==true)
{
document.getElementById('moreTxt').style.display="block";
}
else if (document.form.more[1].checked==true)
{
document.getElementById('moreTxt').style.display="none";
}
}
</script>
do want to enter something more ?
<form name="form">
<input type="radio" value="yes" name="more" onclick="add_more()" /> Yes
<input type="radio" value="No" name="more" onclick="add_more()" /> No
<div id="moreTxt" style="display:none">
hi you can enter more here
<textarea rows="3" cols="4">
</textarea>
</div>
</form>
The Problem is if I click on 'yes', and for some reason I refresh the page, then the 'yes' radio button remains checked but moreTxt div hides (i.e. its default visiblity mode).
How should I tackle this problem?
Check the value of the control on document ready and adjust the div visibility accordingly.
This will reset all your input on load:
<script>
function resetChkBox() {
var e=document.getElementsByTagName('input');
var i=0;
while(i<e.length) {
if(e[i++].type=='radio') {
e[i].checked=false;
}
}
}
</script>
<body onload="resetChkBox()">
you should perform you add_more function onDucomentReady
Assuming you're using jquery:
$(document).ready(function() {
add_more();
}
)
or use plain javascript equivalent of document.ready()
If this is to be performed without jquery which should be the case since including jquery for such small thing will be overkill :
document.attachEvent("onDOMContentLoaded", function(){
ready()
});
In ready function check the value of the radio button.

Categories

Resources