Clear contents on click - javascript

In the following code:
<INPUT TYPE="radio" name="1" id="1" VALUE="1" <?php echo $checked1 ?>><font size="2">1</font>
<INPUT TYPE="radio" name="2" id="2" VALUE="2" <?php echo $checked2 ?>><font size="2">2</font>
<TEXTAREA name="names" id="names" rows="15" cols="65"><?php echo $names ?></TEXTAREA>
If the radio button 1 selected for the first time then onclick on textarea its contents should be cleared, but if the user clicks for the second time on the same text area the contents should not be cleared for the same radio button1.
The same should hold good for radio button2. How is this done?

This will fullfill your requirement. just place in body tag
<input type="radio" name="G1" id="1" value="1" /> <font size="2">1</font>
<input type="radio" name="G1" id="2" value="2" /> <font size="2">2</font>
<textarea name="names" id="names" rows="15" cols="65" onfocus="handleOnFocus()"></textarea>
<script type="text/javascript">
var isCleardForButton1 = false;
var isCleardForButton2 = false;
function handleOnFocus() {
var objTA = document.getElementById("names");
var objRadio1 = document.getElementById("1");
var objRadio2 = document.getElementById("2");
if (isCleardForButton1 == false && objRadio1.checked == true) {
objTA.value = "";
isCleardForButton1 = true;
}
if (isCleardForButton2 == false && objRadio2.checked == true) {
objTA.value = "";
isCleardForButton2 = true;
}
}
</script>

Demo and here is the code:
<TEXTAREA name="names" id="names" rows="15" cols="65" onclick="doIt(this);">Hello There</textarea>
<script>
var isDone = false;
function doIt(field)
{
if (document.getElementById("1").checked == true && isDone == false)
{
field.value = "";
isDone = true;
}
}
</script>
This would clear contents for the first time and not again for the life time of page.

edit: Looks like I mis-understood your requirements. This only applies to the click of the radio button, not to the textarea.
You need to setup a click event to clear the textarea content, and then unbind itself.
With jQuery the event handler would be something like:
$('#names').val('');
$(this).unbind('click');

Related

Save and load checkboxes state to file

I want to save state of selected checkbox to a file (whether as a text file or something else) that contains information on what was checked.
I can't use localstorage or cookies, I need it saved as external file so I can save (and load) several files with different checkmarks selected.
It's pretty straightforward, but I can't find any solution that does exactly this, so any help is appreciated.
Simple snippet for reference:
div {
display: table;
}
span {
display: block;
}
input,
label {
display: inline-block;
}
<div>
<span>
<input id="box1" type="checkbox" />
<label for="box1">Checkbox 1</label>
</span>
<span>
<input id="box2" type="checkbox" checked/>
<label for="box2">Checkbox 2</label>
</span>
<span>
<input id="box3" type="checkbox" />
<label for="box3">Checkbox 3</label>
</span>
</div>
<button id="_save">Save</button>
<button id="_load">Load</button>
Ok, I have a solution that does what I needed.
So when you check everything you want from your form, you can save it into localstorage and THEN you can export localstorage as JSON. I found this google extension that handles import and export for the localstorage (in a textual file), but you can always go extra mile and write your own script for that.
Here is JSFiddle for the localstorage so can save whatever input you want and here is chrome extension that handles import and export LocalStorage Manager.
Javascript:
;(function($) {
$.fn.toJSON = function() {
var $elements = {};
var $form = $(this);
$form.find('input, select, textarea').each(function(){
var name = $(this).attr('name')
var type = $(this).attr('type')
if(name){
var $value;
if(type == 'radio'){
$value = $('input[name='+name+']:checked', $form).val()
} else if(type == 'checkbox'){
$value = $(this).is(':checked')
} else {
$value = $(this).val()
}
$elements[$(this).attr('name')] = $value
}
});
return JSON.stringify( $elements )
};
$.fn.fromJSON = function(json_string) {
var $form = $(this)
var data = JSON.parse(json_string)
$.each(data, function(key, value) {
var $elem = $('[name="'+key+'"]', $form)
var type = $elem.first().attr('type')
if(type == 'radio'){
$('[name="'+key+'"][value="'+value+'"]').prop('checked', true)
} else if(type == 'checkbox' && (value == true || value == 'true')){
$('[name="'+key+'"]').prop('checked', true)
} else {
$elem.val(value)
}
})
};
}( jQuery ));
//
// DEMO CODE
//
$(document).ready(function(){
$("#_save").on('click', function(){
console.log("Saving form data...")
var data = $("form#myForm").toJSON()
console.log(data);
localStorage['form_data'] = data;
return false;
})
$("#_load").on('click', function(){
if(localStorage['form_data']){
console.log("Loading form data...")
console.log(JSON.parse(localStorage['form_data']))
$("form#myForm").fromJSON(localStorage['form_data'])
} else {
console.log("Error: Save some data first")
}
return false;
})
});
HTML:
<form action="#" method="get" id="myForm">
<input type="text" name="textfield">
Textfield
<br/>
<input type="number" name="numberfield" />
Numberfield
<br/>
<input type="radio" name="radiofield" value="1" />
<input type="radio" name="radiofield" value="2" />
<input type="radio" name="radiofield" value="3" />
Radiofields
<br/>
<input type="checkbox" name="checkfield">
<input type="checkbox" name="checkfield2">
<input type="checkbox" name="checkfield3">
Checkboxes
<br/>
<select name="selectbox">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
Selectbox
<br/>
<textarea name="textarea"></textarea>
Textarea
<br/>
<hr/>
<button id="_save">Save</button>
<button id="_load">Load</button>
<input type="reset">
</form>

Using jQuery to validate checkboxes and input text values

I need your help,
Is there a way one can possible use the all so powerful jQuery to validate the following conditions before enabling button?
If the user inputs a value in the text box and then checks one of the checkboxes, then enable the button
If the user already has a value present in the text, and then checks one of the checkboxes, then enable the button
How can this be written in jQuery, from my perspective this would some lenghty form field checking no?
Here's the HTML markup:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="button" value="Add To Calendar" disabled>
<br>
<input type="checkbox" name="dategroup"><input type="text" id="date1">
<br>
<input type="checkbox" name="dategroup"><input type="text" id="date2">
<br>
<input type="checkbox" name="dategroup"><input type="text" id="date3">
</body>
</html>
This might get you started. You can make the field validation as complex or simple as you wish.
$('input[type=checkbox]').click(function(){
var tmp = $(this).next('input').val();
//validate tmp, for example:
if (tmp.length > 1){
//alert('Text field has a value');
$('#mybutt').prop('disabled',false);
}else{
//alert('Please provide a long value in text field');
$('#mybutt').prop('disabled', true);
$(this).prop('checked',false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="mybutt" type="button" value="Add To Calendar" disabled>
<br>
<input type="checkbox" name="dategroup"><input type="text" id="date1">
<br>
<input type="checkbox" name="dategroup"><input type="text" id="date2">
<br>
<input type="checkbox" name="dategroup"><input type="text" id="date3">
Try this way..
$('input').on('change input', function() {
$input = $('input');
$button = $('input[type="button"]');
var arr = [];
$input.each(function() {
if ($(this).attr('type') !== 'button') {
arr.push(check($(this)));
arr.indexOf(false) == -1 ? $button.removeAttr('disabled') : $button.attr('disabled', 'disabled');
}
})
})
function check(elem) {
if ($(elem).attr('type') == 'checkbox' && $(elem).is(':checked')) return true;
if ($(elem).attr('type') == 'text' && $(elem).val().trim().length) return true;
return false;
}
$('input').on('change input', function() {
$input = $('input');
$button = $('input[type="button"]');
var arr = [];
$input.each(function() {
if ($(this).attr('type') !== 'button') {
arr.push(check($(this)));
arr.indexOf(false) == -1 ? $button.removeAttr('disabled') : $button.attr('disabled', 'disabled');
}
})
})
function check(elem) {
if ($(elem).attr('type') == 'checkbox' && $(elem).is(':checked')) return true;
if ($(elem).attr('type') == 'text' && $(elem).val().trim().length) return true;
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="Add To Calendar" disabled>
<br>
<input type="checkbox" name="dategroup">
<input type="text" id="date1">
<br>
<input type="checkbox" name="dategroup">
<input type="text" id="date2">
<br>
<input type="checkbox" name="dategroup">
<input type="text" id="date3">

Using radio buttons to change an image

So i have some radio buttons:
<input type="radio" name="option" value="GDP" id="GDP_option" checked>GDP
<input type="radio" name="option" value="Population" id="Population_option" >Population
<input type="radio" name="option" value="None" id="None_option" > None
I also have a submit button:
<input type="submit" name="submit" id="submit" onsubmit="changeFormula()">
and an image:
<img src="formula_gdp.gif" name="formula" id="formula">
When the submit button is pressed i want to change the image src to something else depending on the radio button that is checked. This is what i've tried:
function changeFormula(){
var radio = document.getElementsByName('option');
var formula = document.getElementsByName('formula')
if (radio[1].checked){
formula.src = "formula_gdp.gif";
}
if (radio[2].checked){
formula.src = "formula_pop.gif";
}
if (radio[3].checked){
formula.src = "formula_none.gif";
}
}
You can Do this by using Jquery as like following ..
<script type='text/javascript'>
$(document).ready(function(){
$("input:radio[name=option]").click(function() {
var value = $(this).val();
var image_name;
if(value == 'GDP'){
image_name = "formula_gdp.gif";
}else{
if(value == 'Population'){
image_name = "formula_pop.gif";
}else{
image_name = "formula_none.gif";
}
}
$('#formula').attr('src', image_name);
});
});
</script>
Only you will have needed those three radio button filed and Image tag .. Not needed Submit button...
<input type="radio" name="option" value="GDP" id="GDP_option" checked>GDP
<input type="radio" name="option" value="Population" id="Population_option" >Population
<input type="radio" name="option" value="None" id="None_option" > None
<img src="formula_gdp.gif" name="formula" id="formula">
Hopefully it will be helpful for you.. If you have needed another things... then you can inform me ....
Try this
$(document).ready(function() {
$("input:radio[name=vf]").change(function() { //name = button group name
if (this.value == "0") {
$("#vf").attr( //image file name
'src', '/images/onestep/lime/vf.jpg' //image path
);
}
else if (this.value == "8") {
$("#vf").attr( //image file name
'src', '/images/onestep/vf.jpg' //image path
);
}
else {
$("#vf").attr( //image file name
'src', '/images/onestep/vf.jpg' //image path
);
}
});
use if(document.getElementById('element_id').checked) for better result.
Two changes require:
1) Change var formula = document.getElementsByName('formula') to var formula = document.getElementById('formula');
2) Index of radio starts with 0 not with 1, so radio[1],radio[2],radio[3] should be radio[0],radio[1],radio[2]
Hope that helps.
Add an event <input type="submit" name="submit" id="submit" onsubmit="changeFormula(e)">
function changeFormula(e){
e.stopPropagation();
var radio = document.getElementsByName('option');
var formula = document.getElementsByName('formula')
if (radio[1].checked){
formula.src = "formula_gdp.gif";
}
if (radio[2].checked){
formula.src = "formula_pop.gif";
}
if (radio[3].checked){
formula.src = "formula_none.gif";
}
}
and if u dont mind using Jquery:
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
if($('#GDP_option').is(':checked')) {
$('#formula').attr('src','formula_gdp.gif')
}
if($('#Population_option').is(':checked')) { $('#formula').attr('src','formula_pop.gif')
}
if($('#None_option').is(':checked')) {
$('#formula').attr('src','formula_none.gif')
}
})
})
<input type="radio" name="option" value="GDP" id="GDP_option" checked>GDP
<input type="radio" name="option" value="Population" id="Population_option">Population
<input type="radio" name="option" value="None" id="None_option">None
<input type="submit" name="submit" id="submit" onclick="changeFormula()">
<img src="formula_gdp.gif" name="formula" id="formula">
<script type="text/javascript">
function changeFormula() {
var radio = document.getElementsByName('option');
var formula = document.getElementById('formula')
if (radio[0].checked) {
formula.src = "formula_gdp.gif";
alert(formula.src);
}
if (radio[1].checked) {
formula.src = "formula_pop.gif";
alert(formula.src);
}
if (radio[2].checked) {
formula.src = "formula_none.gif";
alert(formula.src);
}
}
</script>
Change the 'submit' to a button to stop the page from reloading
<input type="button" value ="Click Me" name="submit" id="submit" onclick="changeFormula()" />
And use this for your function
function changeFormula(){
var formula = document.getElementById('formula')
if(document.getElementById('GDP_option').checked)
formula.src = "formula_gdp.gif";
if(document.getElementById('Population_option').checked)
formula.src = "formula_gdp.gif";
if(document.getElementById('None_option').checked)
formula.src = "formula_none.gif";
}
working fiddle:
http://jsfiddle.net/UB2ka/
There is no image, but you can see the src change in firebug
I think folks love jquery, but I needed something lightweight.
Here it is:
<script>
function changeImage(imgName)
{
image = document.getElementById('theimage');
image.src = imgName;
}
</script>
And here's the radio buttons html (slightly modified for privacy)
<input type="radio" name="reader" value="reader1" onClick="changeImage('image0.jpg');">
<br>
<input type="radio" name="reader" value="reader1" onClick="changeImage('image1.jpg');">
<br>
<input type="radio" name="reader" value="reader1" onClick="changeImage('image2.jpg');">
Here's the image:
<img src="image0.jpg" name="theimage" id="theimage">
This worked for me. Click the radio button, the image changes.

Multiple Radio Buttons that change Submit onclick location.href...possible syntax error

I'm using http://www.somacon.com/p143.php javascript for radio buttons to change the submit onclick location.href depending on which radio button is selected. But I think I may have an issue with my syntax as the button isn't working properly (I don't think it is pulling the value from the radio buttons properly). Thanks in advanced!
Here is the code:
<head>
<script type="text/javascript">
<!--
// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function getCheckedValue(radioObj) {
if(!radioObj)
return "";
var radioLength = radioObj.length;
if(radioLength == undefined)
if(radioObj.checked)
return radioObj.value;
else
return "";
for(var i = 0; i < radioLength; i++) {
if(radioObj[i].checked) {
return radioObj[i].value;
}
}
return "";
}
// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
function setCheckedValue(radioObj, newValue) {
if(!radioObj)
return;
var radioLength = radioObj.length;
if(radioLength == undefined) {
radioObj.checked = (radioObj.value == newValue.toString());
return;
}
for(var i = 0; i < radioLength; i++) {
radioObj[i].checked = false;
if(radioObj[i].value == newValue.toString()) {
radioObj[i].checked = true;
}
}
}
//-->
</script>
</head>
<body>
<form name="radioExampleForm" method="get" action="" onsubmit="return false;">
<p><label for="number0"><input type="radio" value="http://www.google.com" name="number" id="number0"> Zero</label>
<label for="number1"><input type="radio" value="http://www.ebay.com" name="number" id="number1"> One</label>
<label for="number2"><input type="radio" value="http://www.gamestop.com" name="number" id="number2"> Two</label>
<label for="number3"><input type="radio" value="http://www.amazon.com" name="number" id="number3"> Three</label>
<label for="number4"><input type="radio" value="http://www.usatoday.com" name="number" id="number4"> Four</label>
<p>
<input type="button" onclick="location.href='+getCheckedValue(document.forms['radioExampleForm'].elements['number']);" value="Show Checked Value">
ORIGNAL SUBMIT CODE THAT MADE AN ALERT BOX RATHER THAN location.href = <input type="button" onclick="alert('Checked value is: '+getCheckedValue(document.forms['radioExampleForm'].elements['number']));" value="Show Checked Value">
</form>
</body>
It's just a syntax error.
Change it to:
onclick="window.location.href = (getCheckedValue(document.forms['radioExampleForm'].elements['number']));"

How to confirm a radio button selection with an alert box

So i have this code:
<html>
<head>
<title>Form</title>
<script type="text/javascript">
function showConfirmationDialog() {
var textbox = document.getElementById('textbox');
var location = document.getElementById('location');
alert('You chosen:'+'\n'+'\n'+'Name: '+textbox.value +'\n'+'Address: ' +location.value+'\n');
}
function formfocus() {
document.getElementById('textbox').focus();
}
window.onload = formfocus;
var option;
</script>
</head>
<body>
Your name:
<input type="text" name="FirstName" id="textbox" <br><br/>
Your Address:
<input type="text" name="address" id="location" <br></br><br></br>
Choose your location:
<form name="Radio" id="destination" action="">
Bristol:
<input type="radio" name="selection" value="bristol" onClick="option=0">
London:
<input type="radio" name="selection" value="london" onClick="option=1">
Birmingham:
<input type="radio" name="selection" value="birmingham" onClick="option=2" />
</form>
<br></br> Click:
<input type="button" value="Submit" onclick="showConfirmationDialog();" /><br></br>
</body>
</html>
... This code basically represents a form for a user to fill in and at the end select one of three option provided via the radio buttons. What I wanted to find out was that how do I get the selection from one radio button which the user will need to select, displayed within the alert box after they press submit.
Something like this...
function getSelRadioValue()
for(i = 0; i< document.forms['Radio'].elements['selection'].length ; i++){
if(document.forms['Radio'].elements['selection'][i].checked == true)
return document.forms['Radio'].elements['selection'][i].value;
}
return null;
}
var selectedRadioValue = getSelRadioValue(); //use this variable in your alert.
if(selectedRadioValue == null)
alert("please select a destination");
else if(confirm("You have selected " + selectedRadioValue))
//deal with success
You need to loop through the selection radios to get the checked value:
var selection = document.Radio.selection;
var selectionResult = "";
for(var i = 0; i < selection.length; i++) {
if(selection[i].checked) {
selectionResult = selection[i].value;
}
}
alert('You chosen:'+'\n'+'\n'+'Name: '+textbox.value +'\n'+'Address: ' +location.value+'\n' + 'Location: '+selectionResult);

Categories