I have a script that converts "Enter" to "Tab", and it works great until I hit a hidden field on a form.
So, is there any way to detect the hidden field, and still use the script(in IE & firefox)?
<script type="text/javascript">
function tabE(obj, e) {
var e = (typeof event != 'undefined') ? window.event : e; // IE : Moz
if (e.keyCode == 13) {
var ele = document.forms[0].elements;
for (var i = 0; i < ele.length; i++) {
var q = (i == ele.length - 1) ? 0 : i + 1; // if last element : if any other
if (obj == ele[i]) {
ele[q].focus();
break
}
}
return false;
}
}
</script>
Change your code to look like the following:
<script type="text/javascript">
function tabE(obj, e) {
var e = (typeof event != 'undefined') ? window.event : e; // IE : Moz
if (e.keyCode == 13) {
var ele = document.forms[0].elements;
for (var i = 0; i < ele.length; i++) {
var q = (i == ele.length - 1) ? 0 : i + 1; // if last element : if any other
if (obj == ele[i] && $(ele[q]).is(":visible")) {
ele[q].focus();
break
}
}
return false;
}
}
</script>
I just added a check to make sure the element you're about to focus is visible (not hidden).
EDIT: If you want to skip hidden fields entirely, use the below code.
function tabE(obj, e) {
var e = (typeof event != 'undefined') ? window.event : e; // IE : Moz
var self = $(obj),
form = self.parents('form:eq(0)'),
focusable, next;
if (e.keyCode == 13) {
focusable = form.find('input,a,select,button,textarea').filter(':visible');
next = focusable.eq(focusable.index(obj) + 1);
if (!next.length) {
next = focusable.first();
}
next.focus();
return false;
}
}
Fiddle:
https://jsfiddle.net/mwatz122/0zqzzmc1/
My proposal is full js:
function tabE(obj, e) {
var e = (typeof event != 'undefined') ? window.event : e; // IE : Moz
if (e.keyCode == 13) {
var ele = document.forms[0].elements;
for (var i = 0; i < ele.length; i++) {
var q = (i == ele.length - 1) ? 0 : i + 1; // if last element : if any other
if (obj == ele[i]) {
var style = window.getComputedStyle(ele[q]);
while (style.display == 'none' || style.visibility != 'visible' || ele[q].type == 'hidden') {
q = (q == ele.length - 1) ? 0 : q + 1; // if last element : if any other
style = window.getComputedStyle(ele[q]);
}
ele[q].focus();
break
}
}
return false;
}
}
window.onload = function() {
var inp = document.getElementsByTagName("input")
for(i=0; i<inp.length; i++) {
inp[i].addEventListener("keyup", function(e) {
tabE(this, e);
});
}
}
<form>
First name:<br>
<input type="text" name="firstname">
<br>
Last name:<br>
<input type="text" name="lastname">
<input type="text" name="myhidden" style="visibility: hidden">
<input type="hidden" name="myhidden1">
<input type="text" name="myhidden2" style="display: none">
</form>
Related
I've created a custom US telephone mask on input using jQuery like -
(___) ___-____
It's working fine on keydown event.
var telMask = "(___) ___-____";
var phoneNumberBuffer = "";
$(document).ready(function () {
$(".telephone").focus(function () { handleFocus(this); });
$(".telephone").blur(function () { handleBlur(this); });
$(".telephone").keydown(function (event) { formatPhoneNumber(this, event); });
});
function mergePhoneMask() {
var tempMask = telMask;
var tempPos;
for (var i = 0; i < phoneNumberBuffer.length; i++) {
tempPos = tempMask.indexOf("_");
tempMask = tempMask.substr(0, tempPos) + phoneNumberBuffer.charAt(i) + tempMask.substr(tempPos + 1);
}
return tempMask;
}
function setPhoneNumCursor(elem) {
var position = $(elem).val().indexOf("_");
if (position < 0) { position = $(elem).val().length; }
if (elem.setSelectionRange) {
elem.focus();
elem.setSelectionRange(position, position);
}
else if (elem.createTextRange) {
var range = elem.createTextRange();
range.collapse(true);
range.moveEnd('character', position);
range.moveStart('character', position);
range.select();
}
}
function formatPhoneNumber(elem, e) {
var tempMask = telMask;
var tempPos;
if (e.which == 8) {
phoneNumberBuffer = phoneNumberBuffer.substr(0, phoneNumberBuffer.length - 1);
elem.value = mergePhoneMask();
}
if ((e.which > 47 && e.which < 58) || (e.which > 95 && e.which < 106)) {
if (phoneNumberBuffer.length < 10) {
// numpad keys don't match to charcode
if (e.which > 95 && e.which < 106) {
phoneNumberBuffer += (e.which - 96).toString();
} else {
phoneNumberBuffer += String.fromCharCode(e.which);
}
elem.value = mergePhoneMask();
}
}
//e.preventDefault();
if (phoneNumberBuffer.length == 10 || e.which == 9) {
//$(elem).parent().next().next().find("input").focus();
} else {
setPhoneNumCursor(elem);
}
}
function handleFocus(elem) {
if (elem.value == "") {
elem.value = telMask;
}
setPhoneNumCursor(elem);
}
function handleBlur(elem) {
if (elem.value == telMask) {
elem.value = "";
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="control-input">
<input name="telephone" maxlength="14" class="telephone" type="tel" size="14" autocomplete="tel">
</div>
Problem is, while continuing to press the backspace/delete, it removes the "(" at the beginning. I'm not sure if I missed anything here! I've some limitations to use other plugins. Thanks!
I've created a JSFiddle here!
I have the following code to admit decimals:
<input id="precio" type="text" class="form-control" onclick="this.select();" onkeypress="return OnlyDecimal(event, '0.0', 4, 2);"/>
<script>
function OnlyDecimal(e, valInicial, nEntero, nDecimal) {
var obj = e.srcElement || e.target;
var key_code = (document.all) ? e.keyCode : e.which;
var key_val = String.fromCharCode(key_code);
var patron2 = /[\d.]/;
var control = (key_code === 46 && (/[.]/).test(obj.value)) ? false : true;
var existePto = (/[.]/).test(obj.value);
//el tab
if (key_code === 8)
return true;
if (valInicial !== obj.value) {
var TControl = obj.value.length;
if (existePto === false && key_code !== 46) {
if (TControl === nEntero) {
obj.value = obj.value + ".";
}
}
if (existePto === true) {
var subVal = obj.value.substring(obj.value.indexOf(".") + 1, obj.value.length);
if (subVal.length >= nDecimal) {
return false;
}
}
return patron2.test(key_val) && control;
}
else {
if (valInicial === obj.value) {
obj.value = '';
}
return patron2.test(key_val) && control;
}
}
</script>
But when it's at the maximum number of digits allowed and with focus selected, it doesn't allow me to enter numbers to replace the one in the input.
Is there a way to validate this? or how to detect when the input is selected to validate it ?.
The goal is to be able to enter digits in the input when everything is selected. Is there any idea or solution? Is it explained?
you can use selectionStart and selectionEnd like below, if that is what you want
<input id="precio" type="text" class="form-control" onclick="this.select();" onkeypress="return OnlyDecimal(event, '0.0', 4, 2);"/>
<script>
function OnlyDecimal(e, valInicial, nEntero, nDecimal) {
var obj = e.srcElement || e.target;
var key_code = (document.all) ? e.keyCode : e.which;
var key_val = String.fromCharCode(key_code);
var patron2 = /[\d.]/;
var control = (key_code === 46 && (/[.]/).test(obj.value)) ? false : true;
var existePto = (/[.]/).test(obj.value);
var haveSelection = obj.selectionEnd - obj.selectionStart;
//el tab
if (key_code === 8)
return true;
if (valInicial !== obj.value) {
var TControl = obj.value.length;
if (existePto === false && key_code !== 46) {
if (TControl === nEntero) {
obj.value = obj.value + ".";
}
}
if (existePto === true) {
var subVal = obj.value.substring(obj.value.indexOf(".") + 1, obj.value.length);
if (subVal.length >= nDecimal && !haveSelection) {
return false;
}
}
return patron2.test(key_val) && control;
}
else {
if (valInicial === obj.value) {
obj.value = '';
}
return patron2.test(key_val) && control;
}
}
</script>
There is a email field where in if we access the site using chrome/IE/Firefox browser it works as expected, But if I access it using IPhone Safari browser the email field reverse the text I entered.
Example image here-
The code for the field Email is
<input
id="emal"
required
type="text"
maxlength="40"
onclick="this.focus();"
onfocus="if(this.value == this.dflt) { this.value='' }; this.onchange();"
onblur="if(this.value.length < 1) { this.value = this.dflt };"
onchange="this.ffoc = true; validate_email();"
onpaste="this.onchange();" oninput="this.onchange();"
onkeypress="this.onchange();">
Validation part of code -
function validate_email() {
if (document.loaded) {
$form[0].$emal.value = "";
$form[0].$emal.valid = null;
updateField($form[1].$emal, $form[1].$emal.value.replace(/\s/ig, ""));
if (isValidEmail($form[1].$emal.value) && $form[1].$emal.value != $form[
1].$emal.dflt) {
$form[0].$emal.value = $form[1].$emal.value;
$form[0].$emal.valid = true;
$form[1].$emal.setAttribute("valid", "true");
} else {
$form[1].$emal.setAttribute("valid", ($form[1].$emal.clik) ? ($form[
1].$emal.required) ? "false" : "warn" : "");
$form[0].$emal.valid = ($form[1].$emal.clik && !$form[1].$emal
.required) ? true : null;
}
$form[1].$emal.$wbox.style.display = ((/false|warn/i).test($form[1]
.$emal.getAttribute("valid"))) ? "block" : "none";
refresh();
}
}
function isValidEmail(str) {
var val = false;
if (str != null) {
var ddStr =
"aero%asia%biz%cat%com%coop%edu%gov%info%int%jobs%mil%mobi%museum%name%net%org%pro%tel%travel%ac%ad%ae%af%ag%cf%cg%ai%al%am%an%ao%aq%ar%as%at%au%aw%ax%az%ba%bb%bd%be%bf%bg%bh%bi%bj%bm%bn%bo%br%bs%bt%bv%bw%by%bz%ca%cc%cd%ch%ci%ck%cl%cm%cn%co%cr%cs%cu%cv%cx%cy%cz%dd%de%dj%dk%dm%do%dz%ec%ee%eg%eh%er%es%et%eu%fi%fj%fk%fm%fo%fr%ga%gb%gd%ge%gf%gg%gh%gi%gl%gm%gn%gp%gq%gr%gs%gt%gu%gw%gy%hk%hm%hn%hr%ht%hu%id%ie%il%im%in%io%iq%ir%is%it%je%jm%jo%jp%ke%kg%kh%ki%km%kn%kp%kr%kw%ky%kz%la%lb%lc%li%lk%lr%ls%lt%lu%lv%ly%ma%mc%md%me%mg%mh%mk%ml%mm%mn%mo%mp%mq%mr%ms%mt%mu%mv%mw%mx%my%mz%na%nc%ne%nf%ng%ni%nl%no%np%nr%nu%nz%om%pa%pe%pf%pg%ph%pk%pl%pm%pn%pr%ps%pt%pw%py%qa%re%ro%rs%ru%tw%tz%ua%ug%uk%us%uy%uz%va%vc%ve%vg%vi%vn%vu%wf%ws%ye%yt%yu%za%zm%zw",
ckStr = (ddStr).split("%");
if (str.length > 5 && (
/^\w+([\.\-\'\+]?\w+)*#\w+([\.\-]?\w+)*(\.\w+)+$/i).test(str)) {
for (var i = 0; i < ckStr.length; i++) {
if (str.substring(str.lastIndexOf(".") + 1) == ckStr[i]) {
val = true;
break;
}
}
}
}
return val
}
I really appreciate helping me sorting this or providing any references.
I have some java script to help the user with the phone number and prevent the form from being submitted in till the field has a valid phone number.
How ever even with a valid number it keeps telling me to use the format thats already predetermined. What am I doing worng im going to assume it has something to do with the pattern.
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// Node/CommonJS
factory(require('jquery'));
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
var ua = navigator.userAgent,
iPhone = /iphone/i.test(ua),
chrome = /chrome/i.test(ua),
android = /android/i.test(ua),
caretTimeoutId;
$.mask = {
//Predefined character definitions
definitions: {
'9': "[0-9]",
'a': "[A-Za-z]",
'*': "[A-Za-z0-9]"
},
autoclear: true,
dataName: "rawMaskFn",
placeholder: '_'
};
$.fn.extend({
//Helper Function for Caret positioning
caret: function(begin, end) {
var range;
if (this.length === 0 || this.is(":hidden") || this.get(0) !== document.activeElement) {
return;
}
if (typeof begin == 'number') {
end = (typeof end === 'number') ? end : begin;
return this.each(function() {
if (this.setSelectionRange) {
this.setSelectionRange(begin, end);
} else if (this.createTextRange) {
range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', begin);
range.select();
}
});
} else {
if (this[0].setSelectionRange) {
begin = this[0].selectionStart;
end = this[0].selectionEnd;
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
begin = 0 - range.duplicate().moveStart('character', -100000);
end = begin + range.text.length;
}
return { begin: begin, end: end };
}
},
unmask: function() {
return this.trigger("unmask");
},
mask: function(mask, settings) {
var input,
defs,
tests,
partialPosition,
firstNonMaskPos,
lastRequiredNonMaskPos,
len,
oldVal;
if (!mask && this.length > 0) {
input = $(this[0]);
var fn = input.data($.mask.dataName)
return fn?fn():undefined;
}
settings = $.extend({
autoclear: $.mask.autoclear,
placeholder: $.mask.placeholder, // Load default placeholder
completed: null
}, settings);
defs = $.mask.definitions;
tests = [];
partialPosition = len = mask.length;
firstNonMaskPos = null;
mask = String(mask);
$.each(mask.split(""), function(i, c) {
if (c == '?') {
len--;
partialPosition = i;
} else if (defs[c]) {
tests.push(new RegExp(defs[c]));
if (firstNonMaskPos === null) {
firstNonMaskPos = tests.length - 1;
}
if(i < partialPosition){
lastRequiredNonMaskPos = tests.length - 1;
}
} else {
tests.push(null);
}
});
return this.trigger("unmask").each(function() {
var input = $(this),
buffer = $.map(
mask.split(""),
function(c, i) {
if (c != '?') {
return defs[c] ? getPlaceholder(i) : c;
}
}),
defaultBuffer = buffer.join(''),
focusText = input.val();
function tryFireCompleted(){
if (!settings.completed) {
return;
}
for (var i = firstNonMaskPos; i <= lastRequiredNonMaskPos; i++) {
if (tests[i] && buffer[i] === getPlaceholder(i)) {
return;
}
}
settings.completed.call(input);
}
function getPlaceholder(i){
if(i < settings.placeholder.length)
return settings.placeholder.charAt(i);
return settings.placeholder.charAt(0);
}
function seekNext(pos) {
while (++pos < len && !tests[pos]);
return pos;
}
function seekPrev(pos) {
while (--pos >= 0 && !tests[pos]);
return pos;
}
function shiftL(begin,end) {
var i,
j;
if (begin<0) {
return;
}
for (i = begin, j = seekNext(end); i < len; i++) {
if (tests[i]) {
if (j < len && tests[i].test(buffer[j])) {
buffer[i] = buffer[j];
buffer[j] = getPlaceholder(j);
} else {
break;
}
j = seekNext(j);
}
}
writeBuffer();
input.caret(Math.max(firstNonMaskPos, begin));
}
function shiftR(pos) {
var i,
c,
j,
t;
for (i = pos, c = getPlaceholder(pos); i < len; i++) {
if (tests[i]) {
j = seekNext(i);
t = buffer[i];
buffer[i] = c;
if (j < len && tests[j].test(t)) {
c = t;
} else {
break;
}
}
}
}
function androidInputEvent(e) {
var curVal = input.val();
var pos = input.caret();
if (oldVal && oldVal.length && oldVal.length > curVal.length ) {
// a deletion or backspace happened
checkVal(true);
while (pos.begin > 0 && !tests[pos.begin-1])
pos.begin--;
if (pos.begin === 0)
{
while (pos.begin < firstNonMaskPos && !tests[pos.begin])
pos.begin++;
}
input.caret(pos.begin,pos.begin);
} else {
var pos2 = checkVal(true);
var lastEnteredValue = curVal.charAt(pos.begin);
if (pos.begin < len){
if(!tests[pos.begin]){
pos.begin++;
if(tests[pos.begin].test(lastEnteredValue)){
pos.begin++;
}
}else{
if(tests[pos.begin].test(lastEnteredValue)){
pos.begin++;
}
}
}
input.caret(pos.begin,pos.begin);
}
tryFireCompleted();
}
function blurEvent(e) {
checkVal();
if (input.val() != focusText)
input.change();
}
function keydownEvent(e) {
if (input.prop("readonly")){
return;
}
var k = e.which || e.keyCode,
pos,
begin,
end;
oldVal = input.val();
//backspace, delete, and escape get special treatment
if (k === 8 || k === 46 || (iPhone && k === 127)) {
pos = input.caret();
begin = pos.begin;
end = pos.end;
if (end - begin === 0) {
begin=k!==46?seekPrev(begin):(end=seekNext(begin-1));
end=k===46?seekNext(end):end;
}
clearBuffer(begin, end);
shiftL(begin, end - 1);
e.preventDefault();
} else if( k === 13 ) { // enter
blurEvent.call(this, e);
} else if (k === 27) { // escape
input.val(focusText);
input.caret(0, checkVal());
e.preventDefault();
}
}
function keypressEvent(e) {
if (input.prop("readonly")){
return;
}
var k = e.which || e.keyCode,
pos = input.caret(),
p,
c,
next;
if (e.ctrlKey || e.altKey || e.metaKey || k < 32) {//Ignore
return;
} else if ( k && k !== 13 ) {
if (pos.end - pos.begin !== 0){
clearBuffer(pos.begin, pos.end);
shiftL(pos.begin, pos.end-1);
}
p = seekNext(pos.begin - 1);
if (p < len) {
c = String.fromCharCode(k);
if (tests[p].test(c)) {
shiftR(p);
buffer[p] = c;
writeBuffer();
next = seekNext(p);
if(android){
//Path for CSP Violation on FireFox OS 1.1
var proxy = function() {
$.proxy($.fn.caret,input,next)();
};
setTimeout(proxy,0);
}else{
input.caret(next);
}
if(pos.begin <= lastRequiredNonMaskPos){
tryFireCompleted();
}
}
}
e.preventDefault();
}
}
function clearBuffer(start, end) {
var i;
for (i = start; i < end && i < len; i++) {
if (tests[i]) {
buffer[i] = getPlaceholder(i);
}
}
}
function writeBuffer() { input.val(buffer.join('')); }
function checkVal(allow) {
//try to place characters where they belong
var test = input.val(),
lastMatch = -1,
i,
c,
pos;
for (i = 0, pos = 0; i < len; i++) {
if (tests[i]) {
buffer[i] = getPlaceholder(i);
while (pos++ < test.length) {
c = test.charAt(pos - 1);
if (tests[i].test(c)) {
buffer[i] = c;
lastMatch = i;
break;
}
}
if (pos > test.length) {
clearBuffer(i + 1, len);
break;
}
} else {
if (buffer[i] === test.charAt(pos)) {
pos++;
}
if( i < partialPosition){
lastMatch = i;
}
}
}
if (allow) {
writeBuffer();
} else if (lastMatch + 1 < partialPosition) {
if (settings.autoclear || buffer.join('') === defaultBuffer) {
// Invalid value. Remove it and replace it with the
// mask, which is the default behavior.
if(input.val()) input.val("");
clearBuffer(0, len);
} else {
// Invalid value, but we opt to show the value to the
// user and allow them to correct their mistake.
writeBuffer();
}
} else {
writeBuffer();
input.val(input.val().substring(0, lastMatch + 1));
}
return (partialPosition ? i : firstNonMaskPos);
}
input.data($.mask.dataName,function(){
return $.map(buffer, function(c, i) {
return tests[i]&&c!=getPlaceholder(i) ? c : null;
}).join('');
});
input
.one("unmask", function() {
input
.off(".mask")
.removeData($.mask.dataName);
})
.on("focus.mask", function() {
if (input.prop("readonly")){
return;
}
clearTimeout(caretTimeoutId);
var pos;
focusText = input.val();
pos = checkVal();
caretTimeoutId = setTimeout(function(){
if(input.get(0) !== document.activeElement){
return;
}
writeBuffer();
if (pos == mask.replace("?","").length) {
input.caret(0, pos);
} else {
input.caret(pos);
}
}, 10);
})
.on("blur.mask", blurEvent)
.on("keydown.mask", keydownEvent)
.on("keypress.mask", keypressEvent)
.on("input.mask paste.mask", function() {
if (input.prop("readonly")){
return;
}
setTimeout(function() {
var pos=checkVal(true);
input.caret(pos);
tryFireCompleted();
}, 0);
});
if (chrome && android)
{
input
.off('input.mask')
.on('input.mask', androidInputEvent);
}
checkVal(); //Perform initial check for existing values
});
}
});
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<?php
session_start();
$token= md5(uniqid());
$_SESSION['delete_customer_token']= $token;
session_write_close();
?>
<!DOCTYPE html>
<head>
<title>index</title>
<script src="js/jquery-1.9.0.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/jquery.maskedinput.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$.mask.definitions['~'] = "[+-]";
$("#phone").mask("1 (999) 999-9999");
$("input").blur(function() {
$("#info").html("Unmasked value: " + $(this).mask());
}).dblclick(function() {
$(this).unmask();
});
});
</script>
</head>
<body>
<form id="msform" method="post" action=""/>
<input type="hidden" name="token" value="<?php echo $token; ?>"/>
<input type="hidden" name="miles" value=""/>
<div id="formwrap">
<div id="ftx1">FIRST NAME</div>
<input type="text" name="fname" class="box" maxlength="40" min="9" max="40" placeholder=""/>
</div>
<div id="formwrap">
<div id="ftx1">LAST NAME</div>
<input type="text" name="lname" class="box" maxlength="40" min="9" max="40" placeholder=""/>
</div>
<div id="formwrap">
<div id="ftx1">BUSINESS NAME:</div>
<input id="busname" name="busname" class="element text medium" type="text" maxlength="40" value="" placeholder=""/>
</div>
<div id="formwrap">
<div id="ftx1">TYPE OF BUSINESS:*</div>
<input id="bustype" type="bustype" name="bustype" size="" maxLength="64"
placeholder=""
title="">
</div>
<div id="formwrap">
<div id="ftx1">EMAIL: *</div>
<input id="email" type="" name="email" size="" maxLength="64"
placeholder=""
title="Please provide only a email address" novalidate/>
</div>
<div id="formwrap">
<div id="ftx1">PHONE NUMBER: *</div>
<input id="phone" name="phone" class="element text medium" maxlength="" value="" placeholder="PHONE NUMBER" type="tel" pattern="[\+]\d{2}[\(]\d{2}[\)]\d{4}[\-]\d{4}" title="Phone Number Format:1 (614) 000-0000" />
</div>
<br><br><br><br>
<input id="submit" class="button_text" type="submit" name="submit" value="SUBMIT" />
<div id="error"></div>
<h2>contact you within 24h. Thank You!</h2>
</form>
</body>
</html>
Your regular expression and field mask combination is incorrect.
[\+]\d{2}[\(]\d{2}[\)]\d{4}[\-]\d{4} will never match because (a) your mask is configured for North American-style phone numbers (it will match phone numbers in the same format as +91(12)3456-7890), and (b) your mask is not configured with a + at the beginning of the input.
You may be looking for something similar to the following to validate the field itself:
1 \(\d{3}\) \d{3}\-\d{4}
Regex101
I have this form
<form name="exampleform" id="exampleform" action="example123.html" method="get">
<fieldset>
<legend>Creating The Querystring</legend>
<label for="name_1">Name:</label>
<input type="text" name="name1" id="name_1" tabindex="1" size="40" value="Test1" />
<br />
<br />
<input type="submit" id='view_1' value="Submit" tabindex="2" />
</fieldset>
<br />
<br />
<fieldset>
<legend>Creating The Querystring</legend>
<label for="name_2">Name:</label>
<input type="text" name="name2" id="name_2" tabindex="1" size="40" value="Test2" />
<br />
<br />
<input type="submit" id='view_2' value="Submit" tabindex="2" />
</fieldset>
</form>
When it submits to the next page I want to be able to get the query string for the button that was clicked and not see both strings when the page loads. The script that I am using on the receiving page is:
<script type="text/javascript">
document.write("Name: " + Request.QueryString("name1"));
document.write("Name: " + Request.QueryString("name2"));
</script>
and
/*TITLE: Client-Side Request Object for javascript by Andrew Urquhart (UK)
HOME: http://andrewu.co.uk/tools/request/
COPYRIGHT: You are free to use this script for any use you wish, the only
thing I ask you do is keep this copyright message intact with the script.
Please don't pass it off as your own work, but feel free to enhance it and send
me the updated version. Please don't redistribute - it makes it harder to distribute
new versions of the script. This script is provided as is, with no warranty of any
kind. Use it at your own risk.
VERSION: #1.41 2007-06-28 18:10 UTC*/
function RObj(ea) {
var LS = "";
var QS = new Object();
var un = "undefined";
var x = null; // On platforms that understand the 'undefined' keyword replace 'null' with 'undefined' for maximum ASP-like behaviour.
var f = "function";
var n = "number";
var r = "string";
var e1 = "ERROR: Index out of range in\r\nRequest.QueryString";
var e2 = "ERROR: Wrong number of arguments or invalid property assignment\r\nRequest.QueryString";
var e3 = "ERROR: Object doesn't support this property or method\r\nRequest.QueryString.Key";
var dU = window.decodeURIComponent ? 1 : 0;
function Err(arg) {
if (ea) {
alert("Request Object:\r\n" + arg);
}
}
function URID(t) {
var d = "";
if (t) {
for (var i = 0; i < t.length; ++i) {
var c = t.charAt(i);
d += (c == "+" ? " " : c);
}
}
return (dU ? decodeURIComponent(d) : unescape(d));
}
function OL(o) {
var l = 0;
for (var i in o) {
if (typeof o[i] != f) {
l++;
}
}
return l;
}
function AK(key) {
var auk = true;
for (var u in QS) {
if (typeof QS[u] != f && u.toString().toLowerCase() == key.toLowerCase()) {
auk = false;
return u;
}
}
if (auk) {
QS[key] = new Object();
QS[key].toString = function() {
return TS(QS[key]);
}
QS[key].Count = function() {
return OL(QS[key]);
}
QS[key].Count.toString = function() {
return OL(QS[key]).toString();
}
QS[key].Item = function(e) {
if (typeof e == un) {
return QS[key];
}
else {
if (typeof e == n) {
var a = QS[key][Math.ceil(e)];
if (typeof a == un) {
Err(e1 + "(\"" + key + "\").Item(" + e + ")");
}
return a;
}
else {
Err("ERROR: Expecting numeric input in\r\nRequest.QueryString(\"" + key + "\").Item(\"" + e + "\")");
}
}
}
QS[key].Item.toString = function(e) {
if (typeof e == un) {
return QS[key].toString();
}
else {
var a = QS[key][e];
if (typeof a == un) {
Err(e1 + "(\"" + key + "\").Item(" + e + ")");
}
return a.toString();
}
}
QS[key].Key = function(e) {
var t = typeof e;
if (t == r) {
var a = QS[key][e];
return (typeof a != un && a && a.toString() ? e : "");
}
else {
Err(e3 + "(" + (e ? e : "") + ")");
}
}
QS[key].Key.toString = function() {
return x;
}
}
return key;
}
function AVTK(key, val) {
if (key != "") {
var key = AK(key);
var l = OL(QS[key]);
QS[key][l + 1] = val;
}
}
function TS(o) {
var s = "";
for (var i in o) {
var ty = typeof o[i];
if (ty == "object") {
s += TS(o[i]);
}
else if (ty != f) {
s += o[i] + ", ";
}
}
var l = s.length;
if (l > 1) {
return (s.substring(0, l-2));
}
return (s == "" ? x : s);
}
function KM(k, o) {
var k = k.toLowerCase();
for (var u in o) {
if (typeof o[u] != f && u.toString().toLowerCase() == k) {
return u;
}
}
}
if (window.location && window.location.search) {
LS = window.location.search;
var l = LS.length;
if (l > 0) {
LS = LS.substring(1,l);
var preAmpAt = 0;
var ampAt = -1;
var eqAt = -1;
var k = 0;
var skip = false;
for (var i = 0; i < l; ++i) {
var c = LS.charAt(i);
if (LS.charAt(preAmpAt) == "=" || (preAmpAt == 0 && i == 0 && c == "=")) {
skip=true;
}
if (c == "=" && eqAt == -1 && !skip) {
eqAt=i;
}
if (c == "&" && ampAt == -1) {
if (eqAt!=-1) {
ampAt=i;
}
if (skip) {
preAmpAt = i + 1;
}
skip = false;
}
if (ampAt>eqAt) {
AVTK(URID(LS.substring(preAmpAt, eqAt)), URID(LS.substring(eqAt + 1, ampAt)));
preAmpAt = ampAt + 1;
eqAt = ampAt = -1;
++k;
}
}
if (LS.charAt(preAmpAt) != "=" && (preAmpAt != 0 || i != 0 || c != "=")) {
if (preAmpAt != l) {
if (eqAt != -1) {
AVTK(URID(LS.substring(preAmpAt,eqAt)), URID(LS.substring(eqAt + 1,l)));
}
else if (preAmpAt != l - 1) {
AVTK(URID(LS.substring(preAmpAt, l)), "");
}
}
if (l == 1) {
AVTK(LS.substring(0,1),"");
}
}
}
}
var TC = OL(QS);
if (!TC) {
TC=0;
}
QS.toString = function() {
return LS.toString();
}
QS.Count = function() {
return (TC ? TC : 0);
}
QS.Count.toString = function() {
return (TC ? TC.toString() : "0");
}
QS.Item = function(e) {
if (typeof e == un) {
return LS;
}
else {
if (typeof e == n) {
var e = Math.ceil(e);
var c = 0;
for (var i in QS) {
if (typeof QS[i] != f && ++c == e) {
return QS[i];
}
}
Err(e1 + "().Item(" + e + ")");
}
else {
return QS[KM(e, QS)];
}
}
return x;
}
QS.Item.toString = function() {
return LS.toString();
}
QS.Key = function(e) {
var t = typeof e;
if (t == n) {
var e = Math.ceil(e);
var c = 0;
for (var i in QS) {
if (typeof QS[i] != f && ++c == e) {
return i;
}
}
}
else if (t == r) {
var e = KM(e, QS);
var a = QS[e];
return (typeof a != un && a && a.toString() ? e : "");
}
else {
Err(e2 + "().Key(" + (e ? e : "") + ")");
}
Err(e1 + "().Item(" + e + ")");
}
QS.Key.toString = function() {
Err(e2 + "().Key");
}
this.QueryString = function(k) {
if (typeof k == un) {
return QS;
}
else {
if (typeof k == n) {
return QS.Item(k);
}
var k = KM(k, QS);
if (typeof QS[k] == un) {
t = new Object();
t.Count = function() {
return 0;
}
t.Count.toString = function() {
return "0";
}
t.toString = function() {
return x;
}
t.Item = function(e) {
return x;
}
t.Item.toString = function() {
return x;
}
t.Key = function(e) {
Err(e3 + "(" + (e ? e : "") + ")");
}
t.Key.toString = function() {
return x;
}
return t;
}
else {
return QS[k];
}
}
}
this.QueryString.toString = function() {
return LS.toString();
}
this.QueryString.Count = function() {
return (TC ? TC : 0);
}
this.QueryString.Count.toString = function() {
return (TC ? TC.toString() : "0");
}
this.QueryString.Item = function(e) {
if (typeof e == un) {
return LS.toString();
}
else {
if (typeof e == n) {
var e = Math.ceil(e);
var c = 0;
for (var i in QS) {
if (typeof QS[i] != f && ++c == e) {
return QS[i];
}
}
Err(e1 + ".Item(" + e + ")");
}
else {
return QS[KM(e, QS)];
}
}
if (typeof e == n) {
Err(e1 + ".Item(" + e + ")");
}
return x;
}
this.QueryString.Item.toString = function() {
return LS.toString();
}
this.QueryString.Key = function(e) {
var t = typeof e;
if (t == n) {
var e = Math.ceil(e);
var c = 0;
for (var i in QS) {
if (typeof QS[i] == "object" && (++c == e)) {
return i;
}
}
}
else if (t == r) {
var e = KM(e, QS);
var a = QS[e];
return (typeof a != un && a && a.toString() ? e : "");
}
else {
Err(e2 + ".Key(" + (e ? e : "") + ")");
}
Err(e1 + ".Item(" + e + ")");
}
this.QueryString.Key.toString = function() {
Err(e2 + ".Key");
}
this.Version = 1.4;
this.Author = "Andrew Urquhart (http://andrewu.co.uk)";
}
var Request = new RObj(false);
How can i only display the string for the button that was clicked and not see both strings?
For identifying the button that's clicked, you need to have two forms. name1 and view_1 should be enclosed in one form and the other form should have name2 and view_2. This is the only way to identify the clicked button. If name1 is present then view_1 is clicked, if name2 is present then view_2 is clicked.
UPDATE: Added code sample
<form name="exampleform" id="exampleform" action="example123.html" method="get">
<fieldset>
<legend>Creating The Querystring</legend>
<label for="name_1">Name:</label>
<input type="text" name="name1" id="name_1" tabindex="1" size="40" value="Test1" />
<br />
<br />
<input type="submit" id='view_1' value="Submit" tabindex="2" />
</fieldset>
</form>
<br />
<br />
<form name="exampleform1" id="exampleform1" action="example123.html" method="get">
<fieldset>
<legend>Creating The Querystring</legend>
<label for="name_2">Name:</label>
<input type="text" name="name2" id="name_2" tabindex="1" size="40" value="Test2" />
<br />
<br />
<input type="submit" id='view_2' value="Submit" tabindex="2" />
</fieldset>
</form>
You are placing both name fields in one form. If you want just the one value, use two forms.
I rewrote your example page
Now you have 2 forms exampleform and exampleform2. Both submit data to the same page example123.html
Note also in the second form I renamed everything from name_2 to name_1 keeping it consistant with the first form
<form name="exampleform" id="exampleform" action="example123.html" method="get">
<fieldset>
<legend>Creating The Querystring</legend>
<label for="name_1">Name:</label>
<input name="name1" id="name_1" tabindex="1" size="40" value="Test1" type="text">
<br>
<br>
<input value="Submit" tabindex="2" type="submit">
<input value="Reset" tabindex="2" type="reset">
</fieldset>
</form>
<form name="exampleform2" id="exampleform2" action="example123.html" method="get">
<br>
<br>
<fieldset>
<legend>Creating The Querystring</legend>
<label for="name_1">Name:</label>
<input name="name1" id="name_1" tabindex="1" size="40" value="Test2" type="text">
<br>
<br>
<input value="Submit" tabindex="2" type="submit">
<input value="Reset" tabindex="2" type="reset">
</fieldset>
</form>
Now in your response page all you need to look for is
document.write("Name: " + Request.QueryString("name1"));
name2 no longer exists
[UPDATE]
As per a comment you made below. You can not have more then one submit button per form where they submit different data unless you validate the data onsubmit.
There is a serious security problem with what you are trying to do, as I will explain below. But you can still utilize your technique if you follow through.
Using your current code, you could do it by making sure the second file is named "example123.html", is saved in the same directory as the other file, and that your document.write() calls occur after the Request object is defined. Also check for null values, which are made particularly difficult by this class which returns an object rather than a string, so it can not be as easily compared with null.
var name1 = Request.QueryString("name1"),
name2 = Request.QueryString("name2");
if (name1+'' != 'null') {
document.write("Name: " + name1);
}
if (name2+'' != 'null') {
document.write("Name: " + name2);
}
That being said the code you are using follows a number of (other) bad practices, and while convenient perhaps for some people in mimicking the ASP Request behavior is really better abandoned in favor of other more standard practices.
We made a similar function for those coming instead from a PHP background (see http://phpjs.org/functions/import_request_variables:431 ) which if you use the following code, will let you access your variables like this:
ini_set('phpjs.getVarsObj', $_GET = {});
import_request_variables('g');
if ($_GET['name1']) {
document.write(htmlspecialchars($_GET['name1']));
}
if ($_GET['name2']) {
document.write(htmlspecialchars($_GET['name2']));
}
HOWEVER!!.... Please note the important warning though that if you use functions like the one you found (or ours), you are checking the URL for this information, since 1) your form is method=get, and 2) since client-side JavaScript can't by itself detect any other methods of how the data was sent to it, and thus if you are not careful about what you do with the $_GET variable's contents, someone could link someone to your site in such a way as to allow your site's visitor's cookie-stored passwords to be stolen or do other mischief. In other words, as with server-side code, be aware of XSS (Cross-site scripting).
For example, if someone filled in the name on your form with this code:
<script>alert('boo!');</script>
...in some browsers, besides for the person submitting the form, anyone who clicks on the link that results (e.g., if a hacker tempted someone to click it), will see that alert. This may not seem so serious, but if the JavaScript instead detects their cookie password on your site, they could craft it so that the script sends their cookies to their own site.
A somewhat safer solution is to use a function such as http://phpjs.org/functions/htmlspecialchars:426 to escape the potentially unsafe characters like < and & .
document.write(htmlspecialchars($_GET['name1']);
This function was based on the function of the same name in PHP, so it can be used there for the same purppose.
(If you actually WANT to allow HTML to be included in the page, that is more challenging and happens to be a question I just asked: JavaScript-based X/HTML & CSS sanitization )