I have a link which calls some javascript. The javascript populates a form value and submits it. Works fine in all browsers except internet explorer.
All other options on the page are links, thats why I also would like this option to be a link
thanks
<script type="text/javascript">
function timeZone(){
today = new Date()
difference = today.getTimezoneOffset()
var field = document.getElementById("form").timezone
alert("test")
if(difference < 0){
difference = difference * -1
field.value = "GMT+" + pad(Math.floor(difference/60), 2) + ":" + pad(difference%60, 2);
}
else{
field.value = "GMT-" + pad(Math.floor(difference/60), 2) + ":" + pad(difference%60, 2);
}
form = document.getElementById('form');
form.submit();
}
function pad(num, digits) {
num = String(num); while (num.length < digits) { num="0"+num; }; return num;
}
</script>
<form method="get" action="ViewLog.do?page=1" id="form">
<input id="timezone" name="timezone" type="hidden" value=""></input>
<img id="activityHistoryImage" Class = "navImage" src="imgs/history.png" alt="Activity history"/>
Activity history<br/>
<small class="navSubText">See your most recent activities </small>
</form>
Internet Explorer may or may not have issues with the fact that you've given an id of 'form' to your form element; I imagine it probably does. In general, it's best to avoid using tag names as the value on id or name attributes.
Also, your hidden input element has an id, yet you're not using it to reference it. Change:
var field = document.getElementById("form").timezone
to
var field = document.getElementById("timezone");
Declare variables with var.
Place ; where they should be.
Related
I am trying to create a form which will store values in an empty array but the values must be between 0 to 5 and comma separated. the problem is it alerts if values is more than 5 but still stores the value in the array. I want it to alert and then restore the form value.
Here is my code:
<form name ="form1" onsubmit="return validateForm()">
<input type="number" name="text" id="inputText" name="inputText" />
<button onclick="pushData();">Insert</button>
<p id="pText"></p>
</form>
And javascript:
function validateForm () {
var form = document.forms["form1"]["inputText"].value;
if(form <0 && form >= 6) {
alert('value should must be between 0 to 5');
return false;
}
}
// create an empty array
var myArr = [];
function pushData() {
// get value from the input text
var inputText = document.getElementById('inputText').value;
// append data to the array
myArr.push(inputText);
var pval = "";
for(i = 0; i < myArr.length; i++) {
pval = pval + myArr[i];
}
// display array data
document.getElementById('pText').innerHTML = "Grades: " + pval ;
}
Try
if (form <0 || form >= 6)
I think it may work better if you reorganize where the functions are being bound.
Event propagation order:
The button is clicked, and the value is pushed into the array.
The form's submit event triggers, and validates the values, but it's too late.
There are many ways to approach this one, but the simplest would be to call pushData at the end of your validateForm.
Adjusted the condition, because there's no way for a number to
be less than 0 AND greater than or equal to 6 at the same time.
Also added event.preventDefault to stop form submission.
JavaScript
function validateForm (event) {
event.preventDefault();
var form = document.forms["form1"]["inputText"].value;
if (form < 0 || form > 5) {
alert('value should must be between 0 to 5');
return false;
}
pushData();
}
HTML
<form name="form1" onsubmit="validateForm(event)">
<input type="number" id="inputText" />
<button type="submit">Insert</button>
<p id="pText"></p>
</form>
JSFiddle
Note that per the MDN:
A number input is considered valid when empty and when a single number
is entered, but is otherwise invalid.
With this particular form element you may add min and max attributes so that the user must enter a value within a specified range. Therefore, the current contents of the OP's validateForm() function are superfluous. Additionally, that function has a problematic line of code:
if(form <0 && form >= 6) {
You cannot have a value that is both less than zero and greater than or equal to six. Use instead a logical OR, i.e. "||" operator for the logic to work.
The following code allows for a user to select numeric values in the range that the OP specifies and then it displays them in a comma-separated format, as follows:
var d = document;
d.g = d.getElementById;
var pText = d.g('pText');
pText.innerHTML = "Grades: ";
var inputText = d.g("inputText");
var myArr = [];
function pushData() {
var notrailingcomma = "";
myArr.push(inputText.value);
if (myArr.length > 1) {
notrailingcomma = myArr.join(", ").trim().replace(/,$/g,"");
pText.innerHTML = "Grades: " + notrailingcomma;
}
else
{
pText.innerHTML += inputText.value;
}
}
d.forms["form1"].onsubmit = function(event) {
event.preventDefault();
pushData();
};
p {
padding: 1em;
margin:1em;
background:#eeeeff;
color: #009;
}
<form name="form1">
<input type="number" id="inputText" name="inputText" min=0 max=5 value=0>
<button type="submit">Insert</button>
</form>
<p id="pText"></p>
A couple of points with respect to the form:
The OP's HTML has an error in the input field: it has two names. I dropped the one with a name of "text".
I like what #thgaskell recommends with respect to changing "Insert" into a submit button, preventing the default action of submitting the form, and associating pushData with the form's onsubmit event. So, I've modified the code accordingly.
I'm working on a form using Parsley form validation and am running into one last issue before it's all good to go. This is my first time using Parsley too.
I have this bit of custom script to autofill hyphens and parentheses:
<script type="text/javascript">
$("#inf_field_Phone1").on("change keyup paste", function () {
var output;
var input = $("#inf_field_Phone1").val();
input = input.replace(/[^0-9]/g, '');
var area = input.substr(0, 3);
var pre = input.substr(3, 3);
var tel = input.substr(6, 4);
if (area.length < 3) {
output = "(" + area;
} else if (area.length == 3 && pre.length < 3) {
output = "(" + area + ")" + " " + pre;
} else if (area.length == 3 && pre.length == 3) {
output = "(" + area + ")" + " " + pre + "-" + tel;
}
$("#inf_field_Phone1").val(output);
});
</script>
When tabbing through the form fields though to double check that all works well and I get to the phone number field, the first parenthesis autofills, and then when I submit the form, Parsley accepts that as a valid phone number. Here is the HTML:
<form accept-charset="UTF-8" id='become-partner-form' method="POST" name='Form'>
<div class="col-md-6">
<input type="tel" class="form-control tc-custom-focus" id="inf_field_Phone1" name="inf_field_Phone1" placeholder="Phone*" data-parsley-trigger='change' data-parsley-required>
</div>
And this may be unrelated but just in case, here is the js that is binding Parsley to the form:
<script type="text/javascript">
$(function () {
$('#become-partner-form').parsley().on('field:validated', function() {
var ok = $('.parsley-error').length === 0;
$('.bs-callout-warning').toggleClass('invisible', ok);
})
});
</script>
Please let me know if you need a jsfiddle or anything to help out (I don't post here much!)
Any ideas on how to prevent the form submit without a full valid phone number?
First, you probably want to use the input event instead of change (useless in your case btw), keyup and paste.
Parsley uses the inputevent, so as long as your code runs before parsley's (i.e. if you bind your autofill code before Parsley), you should be ok.
I want that the user can see the value of a variable by writing it's name in a textarea, simpliefied:
var money = "300$";
var input = "money"; //user wants to see money variable
alert(input); //This would alert "money"
Is it even possible to output (in this example) "300$"?
Thanks for help!
Instead of seprate variables, use an object as an associative array.
var variables = {
'money': '300$'
}
var input = 'money';
alert(variables[input]);
You can use an object and then define a variable on the go as properties on that object:
var obj = {}, input;
obj.money = "300$";
input = "money";
alert(obj[input]);
obj.anotherMoney = "400$";
input = "anotherMoney";
alert(obj[input]);
A simple way,you can still try this one :
var money = "300$";
var input = "money"; //user wants to see money variable
alert(eval(input)); //This would alert "money"
Here is an answer who use the textarea as asked.
JSFiddle http://jsfiddle.net/7ZHcL/
HTML
<form action="demo.html" id="myForm">
<p>
<label>Variable name:</label>
<textarea id="varWanted" name="varWanted" cols="30" rows="1"></textarea>
</p>
<input type="submit" value="Submit" />
</form>
<div id="result"></div>
JQuery
$(function () {
// Handler for .ready() called.
var variables = {
'money': '300$',
'date_now': new Date()
}
//Detect all textarea's text variation
$("#varWanted").on("propertychange keyup input paste", function () {
//If the text is also a key in 'variables', then it display the value
if ($(this).val() in variables) {
$("#result").html('"' + $(this).val() + '" = ' + variables[$(this).val()]);
} else {
//Otherwise, display a message to inform that the input is not a key
$("#result").html('"' + $(this).val() + '" is not in the "variables" object');
}
})
});
I have a page with already other JavaScripts correctly working... apart from this one:
<script>
function add(numDaysToAdd) {
var data_in = new Date (document.WADAInsertForm.data_in.value);
var data_out = data_in.setDate(data_in.getDate()+numDaysToAdd);
var final_day = data_out.getDate();
var final_month = data_out.getMonth() + 1;
var final_year = data_out.getFullYear();
document.WADAInsertForm.data_out.value = final_year+'-'+final_month+'-'+final_day;
}
</script>
This script is triggered by an OnChange call on a checkbox together with a OnClick event. To clarify:
<input type="checkbox" name="product" value="Insurance plan: 1 month" id="product" onClick="this.form.price.value='41.40'" onChange="add(+30)">
When I test the page in Chrome it does all the homeworks: insert the price value in the "price" field and update the "data_out" field with the proper value.
When I do the same in Firefox and Safari... it works only the "price" setting.
Any suggestions or help?
onChange="add(+30)"
Here +30 doesn't represent any String or any Integer in your script it would through a type error, to add days to the current date you could use this script
<script type="text/javascript" language="javascript">
function AddDays(toAdd) {
if (!toAdd || toAdd == '' || isNaN(toAdd)) return;
var d = new Date();
d.setDate(d.getDate() + parseInt(toAdd));
document.getElementById("result").innerHTML = d.getDate() + "/" + d.getMonth() + "/" + d.getFullYear();
}
</script>
---------------------- UI ---------------
<div id="result">
</div>
<input type="text" value="0" onkeyup="AddDays(this.value);" />
onClick isn't valid. Use onclick.
And I find it strange to have both onclick and onchange on a checkbox. You should include your onclick in the onchange.
I have seen a few of these jquery things going on, and just wondered if there was a simple number formatting script.
Essentially, all we wish to do, is format ( client side ) for checking purposes only, the number entered in a field. To show somewhere else on the page ( presumably in a div ) the formatted price they entered.
So lets say, field
input id="price" name="price" size="50" type="text" class="medium" /
And they enter 1234560
I want to show somewhere else on the page, :
You Entered : $1,234,560.00 as the price. Is this correct ?
This is only for visual purposes only. Alternatively, changing the value of what they type and formatting it "live" could be an option, however the value we want to send to the db is pure numerics, ie: 1234560
Setup a function like this one
Javascript format currency
function CurrencyFormatted(amount) {
var i = parseFloat(amount);
if(isNaN(i)) { i = 0.00; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
i = parseInt((i + .005) * 100);
i = i / 100;
s = new String(i);
if(s.indexOf('.') < 0) { s += '.00'; }
if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
s = minus + s;
return s;
}
Then set an onchange for jQuery something like this
jQuery(document).ready(function(){
jQuery('#price').change(function(){
jQuery('#mydivsomewhere').val(CurrencyChange(jQuery('#price').val()));
});
});
Not sure if that is 100% correct, haven't tested it. But should call CurrencyFormat whenever the text in your input box changes. Should pass in the val of the textbox with id of price and set a div of id mydivsomewhere with the formatted value.