checkbox checked - assign value to variable and send in a submit - javascript

I have this piece of code, and I'm trying to assign a value to variable days (if one of the combinations of checkbox checked are true), and send by submit to another asp.
The problem is that the variable doesn't take any value. Here's the code:
<html>
<head>
<script type="text/javascript">
function validatedays(days) {
var dias=3
if(document.getElementById("chkmonday").checked && document.getElementById("chktuesday").checked)
{ var days=1;}
if(document.getElementById("chkwednesday").checked && document.getElementById("chkthursday").checked)
{ var days=2;}
if(document.getElementById("chkfriday").checked) {
var days=3 }
datos.submit()
}
</script>
</head>
<body>
<form method="post" id="data" name="data" action="blabla.asp">
<input type="text" name="txtsurname" id="txtsurname" size="20" /><br />
<input type="text" name="txtcuota" id="txtcuota" size="20" /><br />
<br />
<input type="checkbox" value="chklunes" name="chkmonday" /><br/>
<input type="checkbox" value="chkmartes" name="chktuesday" /><br/>
<input type="checkbox" value="chkmiercoles" name="chkwednesday" /><br/>
<input type="checkbox" value="chkjueves" name="chkthursday" /><br/>
<input type="checkbox" value="chkviernes" name="chkfriday" /><br/>
<br/>
<input type="submit" value="Calcular" onclick="javascript:validatedays(days)" />
<input type="reset" value="Clean" />
</form>
</body>
</html>

The var keyword declares a variable in the current scope. You need to declare days in the scope of your whole function. Then you need a way to pass your value in the form: this is usually done with a input type="hidden".
function validatedays() {
var days;
if(document.getElementById("chkmonday").checked && document.getElementById("chktuesday").checked) {
days=1;
} else if(document.getElementById("chkwednesday").checked && document.getElementById("chkthursday").checked) {
days=2;
} else if(document.getElementById("chkfriday").checked) {
days=3;
}
// Assign days to the value of a (hidden) input in the form
document.getElementById('data').submit();
}
Your button being a type="submit", I think you don't need the last line (unless you cancel the event).

The problem is that when you do var <name of the variable> you are redeclaring it when you don't have to. So remove the var keyword.
Also, you were missing some ; and most importantly, you hadn't defined datos (which, I guess was supposed to be the form).
var datos = document.getElementById('data');
function validatedays(days) {
if (document.getElementById('chkmonday').checked
&& document.getElementById('chktuesday').checked) {
days = 1;
}
if (document.getElementById("chkwednesday").checked
&& document.getElementById("chkthursday").checked) {
days = 2;
}
if (document.getElementById("chkfriday").checked) {
days = 3;
}
datos.submit();
}

Related

Type on textfield when it has focus using button Javascript

I have one button that displays number "1" when clicked and three text boxes. I want when the button is clicked the number is displayed on the text box that has focus. Can someone help me please.
function run(){
document.calc.txt1.value += "1";
}
<input type=button name="btn1" value="1" OnClick="run()"id="button"><br />
<form name="calc">
<input type="text" id="txt1" name="txt1">
<input type="text" id="txt2" name="txt2">
<input type="text" id="txt3" name="txt3">
</form>
t3">
When you click a button, the previous input looses focus. You could try to store the last focused input element before the click:
(this needs some more work)
var lastFocus = null;
document.addEventListener("blur", function(event) {
// Here, you'll need to find out if the blurred element
// was one of your valid inputs. It's probably best to
// identify them by a class name
if (event.target.type === "text") {
lastFocus = event.target;
}
}, true);
function run() {
// When the user hasn't yet focused on a text input,
// the first one is used by default
(lastFocus || document.calc.txt1).value += "1";
}
<input type=button name="btn1" value="1" OnClick="run()"id="button"><br />
<form name="calc">
<input type="text" id="txt1" name="txt1">
<input type="text" id="txt2" name="txt2">
<input type="text" id="txt3" name="txt3">
</form>
var currId;
function setId(curr){
currId=curr.id;
}
function run(){
if(currId)
{
document.getElementById(currId).value +='1';
}
//document.calc.txt1.value += "1";
//document.activeElement.value += "1";
}
<input type=button name="btn1" value="1" OnClick="run()"id="button"><br />
<form name="calc">
<input type="text" id="txt1" name="txt1" onblur="setId(this)">
<input type="text" id="txt2" name="txt2" onblur="setId(this)">
<input type="text" id="txt3" name="txt3" onblur="setId(this)">
</form>
Ok, so this code snippet should do what you want. The main thing to note though is that whenever you click the button, the input box becomes blurred that you had selected.
Essentially what this code does here is set the onfocus attribute to allow you to figure out which input box was last focused, rather than which input box IS focused, because none are. Also, I'd recommend changing the button to a 'button' tag because it separates it in terms of tag name from the other input boxes.
Hope this helped, and let me know if you have any questions.
var inputs = document.getElementsByTagName('input');
for(var i = 1 ; i < inputs.length; i ++){
inputs[i].onfocus = function(){
this.setAttribute('class','focused');
}
}
function run(){
var inputBox = document.getElementsByClassName('focused')[0];
if(inputBox){
inputBox.value += "1";
inputBox.setAttribute('class','blurred');
}
}
<input type=button name="btn1" value="1" OnClick="run()"id="button"><br />
<form name="calc">
<input type="text" id="txt1" name="txt1">
<input type="text" id="txt2" name="txt2">
<input type="text" id="txt3" name="txt3">
</form>

Using javascript functions in HTML

I am creating a small webpage that will add two input fields together and place the result in another input field. This is what I have:
<html>
<head>
<title>Calculator</title>
<script type="text/javascript">
function add(){
var num1 = parseInt(document.calc.num1.value);
var num2 = parseInt(document.calc.num2.value);
var answer = (num1+num2);
document.getElementById('res').value = answer;
}
</script>
</HEAD>
<BODY>
<FORM NAME="calc">
<INPUT TYPE ="button" NAME="add" Value="+" onClick="add()">
<hr/>
<INPUT TYPE ="text" NAME="num1" Value="">
<INPUT TYPE ="text" NAME="num2" Value="">
<hr/>
<INPUT TYPE ="text" ID="res" NAME="result" VALUE="">
</FORM>
</BODY>
</HTML>
And I am getting the following error when I press the + button.
Uncaught TypeError: object is not a function
Try changing the function name from add to addNumbers or something like that.
onclick is the right attribute to handle click
onClick="add()"
Switch this bit to
onclick="add()"
The problem is the name of the function "add()", change the name and you will see that it will works!
HTML
<p>
<label for="field1">Field 1</label>
<input type="number" id="field1"/>
</p>
<p>
<label for="field2">Field 2</label>
<input type="number" id="field2"/>
</p>
<p>
<label for="total">Total</label>
<input readonly type="number" id="total"/>
</p>
<p>
<input type="button" id="calc" value="Calculate"/>
</p>
Javascript
Goes in a script tag in head.
function sumFields(fields) {
var total = 0;
// goes through each field and adds them to the total
for(var i=0,l=fields.length; i<l; i++)
{ total += parseInt(document.getElementById(fields[i]).value); }
document.getElementById('total').value = total;
}
function calc_click() {
// runs when the button is clicked
sumFields(['field1','field2']);
}
// main function
function init() {
// add button functionality
document.getElementById('calc').addEventListener('click',calc_click,false);
}
// fires when the DOM is loaded
document.addEventListener('DOMContentLoaded',init,false);

How to set sum value on text feild when second value is set text?

This is my demo cord.
<input type="text" id="my_input1" />
<input type="text" id="my_input2" />
<input type="text" id="total" />
<input type="button" value="Add Them Together" onclick="doMath();" />
<script type="text/javascript">
function doMath()
{
// Capture the entered values of two input boxes
var my_input1 = document.getElementById('my_input1').value;
var my_input2 = document.getElementById('my_input2').value;
// Add them together and display
var sum = parseFloat(my_input1) + parseFloat(my_input2);
document.getElementById('total').value=sum;
}
I want to work this function when my_input2 is enter it's value. Just like onclick method for button is there any event to set value to total tetxfeild after key release event?
<script type="text/javascript">
$(document).ready(function () {
$("#my_input2").blur(function () {
var sum = parseInt($("#my_input1").val()) + parseInt($("#my_input2").val());
$("#total").val(sum);
});
});
</script>
<div>
<input type="text" id="my_input1" />
<input type="text" id="my_input2" />
<input type="text" id="total" />
<input type="button" value="Add Them Together" />
</div>
And also u should frame ur question correctly bcz u have added code in button click and asking us it should work after leaving textbox
Put onkeyup() on second input field this will fire your function.
Something like that:
<input type="text" id="my_input2" onkeyup="doMath();" />
try this
<input type="text" id="my_input2" onchange="doMath();" />

Serializing and deserializing a form with its current state

I have this form
<form id=my_form>
<input id=mt type=text><input id=mc type=checkbox><textarea id=mta />
</form>
I want to have a button somewhere else, that can serialize the form WITH its state, that is, if the textarea has a content, or the text has a content or the checkbox is pressed, I want that information to be stored somehow in the string. Later, I would like to restore the information in the form using that string.
I tried with .innerHTML and it didn't work, I always got the original HTML.
I also looked at the serialize method of jQuery, but I was not able to deserialize it "inside" the form.
Thank you in advance!
Kurt
I've made examples for you. Tested - working fine.
You need jQuery library
First here goes the form:
<form id="my_form">
<input id="formText" type="text" name="formText" />
<br />
<label><input id="formCheck" type="checkbox" name="formCheck" /> check 1</label>
<br />
<label><input id="formCheck2" type="checkbox" name="formCheck2" /> check 2</label>
<br />
<textarea name="formTextarea" id="formTextarea" cols="20" rows="3"></textarea>
<br />
<label><strong>Time unit</strong>:</label>
<p>
<label><input type="radio" name="dataView" value="week" checked="checked" /> Week</label>
<label><input type="radio" name="dataView" value="month" /> Month</label>
<label><input type="radio" name="dataView" value="year" /> Year</label>
</p>
<input type="button" value="Serialize" onclick="serializeForm()" />
<input type="button" value="Unserialize" onclick="restoreForm()" />
</form>
After clicking buttons, corresponding function are called in js
And here is the js:
Serialized data is stored in formData variable, and if needed you can store it in cookie, in database etc... And later load it, regarding your requirements
<script type="text/javascript">
var formData;
function serializeForm() {
formData = $('#my_form').serialize();
}
function restoreForm() {
var obj = unserializeFormData(formData);
// Restore items one by one
if(obj.hasOwnProperty('formTextarea')) {
$('#formTextarea').val(obj.formTextarea);
}
if(obj.hasOwnProperty('formText')) {
$('#formText').val(obj.formText);
}
// Radio buttons
if(obj.hasOwnProperty('dataView'))
$('input[value="'+obj.dataView+'"]').attr('checked', true);
// Restore all checkbox. You can also iterate all text fields and textareas together, because the have same principle for getting and setting values by jQuery
$('#my_form input[type="checkbox"]').each(function(){
var checkName = $(this).attr('name');
var isChecked = false;
if(obj.hasOwnProperty(checkName))
isChecked = true;
$(this).attr('checked',isChecked);
});
}
function unserializeFormData(data) {
var objs = [], temp;
var temps = data.split('&');
for(var i = 0; i < temps.length; i++){
temp = temps[i].split('=');
objs.push(temp[0]);
objs[temp[0]] = temp[1];
}
return objs;
}
</script>

Submitting forms and processing

I need to be able to have one submit button for multiple forms. I only took two forms from my coding for the sake of simplicity. Each form has its own unique ID, but each form is very much identical to one another save a few discrepancies. My problem is only the first form is submitted successfully. I realize the reason for that is my input fields have the same name in each and every form so it will not recognize a duplicate input field currently. Is there a way that each field can be submitted successfully even though the input fields are the same, I hope that with help I will be able to submit both 'input_1' values and process it as 'form1:input_1' and 'form2:input_1' respectively.
Thank you very much in advance
<body><form name="form1">
<input type="hidden" name="formID" value="form2"/>
<input type="hidden" name="redirect_to" value=""/>
<INPUT TYPE=TEXT NAME="input_1" SIZE=10 />
<INPUT TYPE=TEXT NAME="input_A" SIZE=15>/<INPUT TYPE=TEXT NAME="input_C"style="width: 1em" maxlength="1"><sup>s</sup>
<INPUT TYPE=TEXT NAME="input_B" SIZE=10 />
<INPUT TYPE="button" VALUE="+" name="SubtractButton" onkeydown="CalculateIMSUB(this.form)">
<INPUT TYPE=TEXT NAME="Answer" SIZE=12>
<input type="hidden" name="val" value="298" />
<INPUT TYPE=TEXT NAME="Answer_2" SIZE=4></form>
<form name="form2">
<input type="hidden" name="formID" value="form2"/>
<input type="hidden" name="redirect_to" value=""/>
<INPUT TYPE=TEXT NAME="input_1" SIZE=10 />
<INPUT TYPE=TEXT NAME="input_A" SIZE=15>/<INPUT TYPE=TEXT NAME="input_C"style="width: 1em" maxlength="1"><sup>s</sup>
<INPUT TYPE=TEXT NAME="input_B" SIZE=10 />
<INPUT TYPE="button" VALUE="+" name="SubtractButton" onkeydown="CalculateIMSUB(this.form)">
<INPUT TYPE=TEXT NAME="Answer" SIZE=12>
<input type="hidden" name="val" value="298" />
<INPUT TYPE=TEXT NAME="Answer_2" SIZE=4></form>
<input type="submit" name="Submit" id="button" value="Submit" onClick="submitAllDocumentForms()"></body>
Javascript code:
<script language="javascript" type="text/javascript">
/* Collect all forms in document to one and post it */
function submitAllDocumentForms() {
var arrDocForms = document.getElementsByTagName('form');
var formCollector = document.createElement("form");
with(formCollector)
{
method = "post";
action = "process.php";
name = "formCollector";
id = "formCollector";
}
for(var ix=0;ix<arrDocForms.length;ix++) {
appendFormVals2Form(arrDocForms[ix], formCollector);
}
document.body.appendChild(formCollector);
formCollector.submit();
}
/* Function: add all elements from ``frmCollectFrom´´ and append them to ``frmCollector´´ before returning ``frmCollector´´*/
function appendFormVals2Form(frmCollectFrom, frmCollector) {
var frm = frmCollectFrom.elements;
var nElems = frm.length;
for(var ix = nElems - 1; ix >= 0 ; ix--)
frmCollector.appendChild(frm[ix]);
return frmCollector;
}
</script>
name is not a standard attribute for the form tag. I suggest that you use id for identiying your forms.
I have not tested the below changes, but I expect them to work:
function appendFormVals2Form(frmCollectFrom, frmCollector) {
var currentEl;
var frm = frmCollectFrom.elements;
var nElems = frm.length;
for(var ix = nElems - 1; ix >= 0 ; ix--) {
currentEl = frm[ix];
currentEl.name = frmCollectFrom.name + ':' + currentEl.name;
frmCollector.appendChild(currentEl);
}
return frmCollector;
}

Categories

Resources