Firefox java script form - javascript

I have the following jsp code below. I am having issues with Firefox sending different parameters in the get method than Interenet Explorer. Any ideas?
Here is the get url:
Internet Explorer:
http://www.example.com/app/search/SkillSearch.do?dispatch=skillSearch2&textSearch=test&search=&searchField=test&searchType=
Firefox:
http://www.example.com/app/search/SearchPeople.do?dispatch=&textSearch=&search=&searchField=test&searchType=
<script>
function doSearch(selection,searchInfo){
// Get the Search Bar Form
var searchForm = document.getElementById('searchBarForm').firstChild;
// Get the dispatch input in the Search Bar Form
var searchFormChildren = searchForm.childNodes;
var dispatch;
for (var i=0; i<searchFormChildren.length; i++) {
if (searchFormChildren[i].name == "dispatch") {
dispatch = searchFormChildren[i];
break;
}
}
// Variable to hold search input
var searchField;
// Set form variables depending on type of search selected
if (selection.selectedIndex == "0") {
dispatch.value = "skillSearch2";
searchForm.action = "/app/search/SkillSearch.do";
for (var i=0; i<searchFormChildren.length; i++) {
if (searchFormChildren[i].name == 'textSearch') {
searchField = searchFormChildren[i];
break;
}
}
}
else if (selection.selectedIndex == "1") {
dispatch.value = "searchPeople";
searchForm.action = '/app/search/SearchPeople.do';
for (var i=0; i<searchFormChildren.length; i++) {
if (searchFormChildren[i].name == 'search') {
searchField = searchFormChildren[i];
break;
}
}
}
else if (selection.selectedIndex == "2") {
dispatch.value="search";
searchForm.action = '/app/search/LinkSearch.do';
for (var i=0; i<searchFormChildren.length; i++) {
if (searchFormChildren[i].name == 'search') {
searchField = searchFormChildren[i];
break;
}
}
}
searchField.value = searchInfo.value;
searchForm.submit();
}
function checkKeyPress(selection, searchInfo) {
if (window.event && window.event.keyCode == 13) {
doSearch(selection, searchInfo);
}
}
</script>
<logic:present name="SSO_TOKEN" scope="session">
<p id="searchBarForm">
<html:form action="/search/SearchPeople.do" method="get">
<input type="hidden" name="dispatch" value=""/>
<input type="hidden" name="textSearch" value="" /> <input type="hidden" name="search" value="" />
<input size="15" name="searchField" value="Search" onfocus="if (this.value == 'Search') this.value = '';" onkeypress="checkKeyPress(searchType, searchField)"/>
<select class="select" name="searchType" size="1" style="font-size: 13px;" onkeypress="checkKeyPress(searchType, searchField)">
<option value="" selected>Subject Matter Experts</option>
<option value="">Users</option>
</select>
<input class="button" type="button" value="Search" onclick="doSearch(searchType, searchField)" />
</html:form>
</p>
</logic:present>

Validate. Validate. Validate. A paragraph cannot contain a form, and different browsers appear to be recovering from that error in different ways.
Additionally, don't assume that the first element and the first child are the same. Some browsers will create a textNode consisting entirely of whitespace when you have: <foo> <bar></bar> </foo>.

David Dorward's answer is spot on. Compare IE and Firefox at http://software.hixie.ch/utilities/js/live-dom-viewer/saved/949 (which is more or less your markup, assuming you're serving up a quirks-mode document)

Related

Form validation error message is overriding in javascript (only )

Hope, you all doing well.
I am trying to validate firstname input field of a form with Javascript. For some reason, error messages doesn't display in order. Some of them override others, only just one error message is displaying, the rest is not.
I'm wondering why? Can anyone shed me some light please?
Here is my code:
// Predefined validator function to check if input is empty or not
var validator = {};
validator.isEmpty = function(input) {
// Stop execution if input isn't string
if (typeof input !== 'string') return false;
if (input.length !== 0) {
for (var i = 0; i < input.length; i++) {
if (input[i] !== " ") {
return false;
}
return true;
}
}
return true;
};
validator.isEmpty(null); // returns false
// Main part to get inputs and apply validation
window.onload = function() {
var signUp = document.getElementById("signUp");
var fName = document.getElementById("fName");
var suButton = document.getElementById("subMit");
// Submit button on the function
suButton.addEventListener('click', function(event) {
isNameValid(fName);
});
signUp.addEventListener('submit', function(event) {
event.preventDefault();
});
function isNameValid(char) {
var val = char.value;
if (validator.isEmpty(val)) {
if (val.length < 2) {
// Display a message if input length is less than 2
char.setCustomValidity("We expect your input should contain at least 2 characters, darling !");
char.style.borderColor = "red";
}
if(!isNaN(val)) {
char.setCustomValidity("Please, enter only characters");
char.style.borderColor = "red";
}
} else {
char.setCustomValidity("");
char.style.borderColor = "green";
}
}
<form id="signUp">
<input type="text" id="fName" name="firstname" placeholder="First name">
<input type="checkbox" name="result" required autofocus> Agree our conditions
<input type="submit" id='subMit' value="SUBMIT">
</form>
It took me a while but I hope following works for you. Let me know if you need help understanding anything. I felt your code was a bit complex so I simplified it.
<script>
function submitForm(){
var formValid = false;
var msg = "";
var fNameElement = document.getElementById("fName");
if(fNameElement){
var fNameValue = fNameElement.value;
if(fNameValue.length < 2){
msg = "We expect your input should contain at least 2 characters, darling !";
}
else if(!(/^[a-zA-Z]+$/.test(fNameValue))){
msg = "Please, enter only characters";
}
else{
formValid = true;
}
if(formValid){
fNameElement.style.borderColor="green";
//do something
}
else{
fNameElement.style.borderColor="red";
alert(msg); // or show it in a div
}
}
}
</script>
<form id="signUp" action="javascript:submitForm()">
<input type="text" id="fName" name="firstname" placeholder="First name">
<input type="checkbox" name="result" required autofocus> Agree our conditions
<input type="submit" id='subMit' value="SUBMIT">
</form>
Fiddle: https://jsfiddle.net/fxumcL3d/3/

Javascript code works on IE but fails on Chrome

This code works fine on IE, but fails on Chrome.
Theory: When you click on the input, the input marks with an X or when you hit again the X is deleted (just like a checkbox) , when any of these conditions are met, the script should send the forms Y ( if X is checked) or N (if X is empty ).
HTML
Note: The values are generated dynamically using the data from a external database).
<input type="text" READONLY id="65535" class="chk" iffalse="N" iftrue="Y" value=""
onclick="fchkboxclick();" />
JavaScript
function fchkboxclick() {
object = window.event.srcElement;
if (object.id == '65535') {
if (object.value == 'X') {
activevalue = object.getAttribute("iffalse");
objet.value = '';
} else {
activevalue = object.getAttribute("iftrue");
object.value = 'X';
}
} else {
if (object.value == 'X') {
sendevent(object.id, 'check', object.getAttribute("iffalse"));
} else {
sendevent(object.id, 'check', object.getAttribute("iftrue"));
}
}
}
When I run this on any version of IE, the forms (sendevent function) receive the value from the attribute (Y or N) but in Chrome I just receive X.
Any help would be appreciated. Thanks.
if you use an onclick event in an element, far easier to do this
<input onclick="dosomething(this);" />
Then your code can do
function dosomething(element) {
// element is the element that was clicked
}
Ok, i done with this:
<html>
<body>
<input type="checkbox" name="chb[]" id="pepe" class='chk' iffalse="N" iftrue="Y" value="0" onchange="validate()" />
<br/> Value sent
<input type="text" id="1234" value="" />
<script type="text/javascript">
var inputcb = document.getElementById('1234');
function validate() {
if (document.getElementById('pepe').checked) {
inputcb.value = document.getElementById('pepe').getAttribute("iftrue");
} else {
inputcb.value = document.getElementById('pepe').getAttribute("iffalse");
}
}
</script>
</body>
</html>

Javascript Validation for all field with Required attribute

I've searched high and low for the answer to this but can't find it anywhere.
I have a form which has the HTML 'required' attributes and it does a fine job of highlighting the fields that need to filled in before submission...or would do, but the system which my form is bolted onto (of which I have no control over) submits the form anyway after a few seconds. It relies on Javascript for it's submission. Therefore I'd like to write a Javascript script to check all fields for a required attribute. Currently I have a script that specifies the fields I want to be mandatory, but if it could look up the attribute instead, that would be brilliant.
In case that input[type=submit] is used, you don't need any JavaScript
<form id="theForm" method="post" acion="">
<input type="firstname" value="" required />
<input type="lastname" value="" required />
<input type="submit" name="submit" value="Submit" />
</form>
Working jsBin
But if input[type=button] is used for submitting the form, use the snippet below
<form id="theForm" method="post" acion="">
<input type="firstname" value="" required />
<input type="lastname" value="" required />
<input type="button" name="button" value="Submit" />
</form>
window.onload = function () {
var form = document.getElementById('theForm');
form.button.onclick = function (){
for(var i=0; i < form.elements.length; i++){
if(form.elements[i].value === '' && form.elements[i].hasAttribute('required')){
alert('There are some required fields!');
return false;
}
}
form.submit();
};
};
Wotking jsBin
Many years later, here is a solution that uses some more modern Javascript:
for (const el of document.getElementById('form').querySelectorAll("[required]")) {
if (!el.reportValidity()) {
return;
}
}
See Vlad's comment for a link to the Constraint Validation API (thanks Vlad, that helped!)
You can use Constraint validation API, which is supported by most browsers.
I'm late to the party but this worked for me.
<input type="firstname" value="" required />
document.getElementById('theForm').reportValidity();
if (check) {
//success code here
return true;
}
Credit to Vlad and a.l.e for pointing me in the right direction with their previous answers. This is a simplified version of their approach.
this will be validating all your form field types
$('#submitbutton').click(function (e) {
e.preventDefault();
var form = document.getElementById("myForm");
var inputs = form.getElementsByTagName("input"), input = null, select = null, not_pass = false;
var selects = form.getElementsByTagName("select");
for(var i = 0, len = inputs.length; i < len; i++) {
input = inputs[i];
if(input.type == "hidden") {
continue;
}
if(input.type == "radio" && !input.checked) {
not_pass = true;
}
if(input.type == "radio" && input.checked){
not_pass = false;
break;
}
if(input.type == "text" && !input.value) {
not_pass = true;
}
if(input.type == "text" && input.value){
not_pass = false;
break;
}
if(input.type == "number" && !input.value) {
not_pass = true;
}
if(input.type == "number" && input.value){
not_pass = false;
break;
}
if(input.type == "email" && !input.value) {
not_pass = true;
}
if(input.type == "email" && input.value){
not_pass = false;
break;
}
if(input.type == "checkbox" && !input.checked) {
not_pass = true;
}
if(input.type == "checkbox" && input.checked) {
not_pass = false;
break;
}
}
for(var i = 0, len = selects.length; i < len; i++) {
select = selects[i];
if(!select.value) {
not_pass = true;
break;
}
}
if (not_pass) {
$("#req-message").show();//this div # in your form
return false;
} else {
//do something here
}
});
If using either the simple "required" solution above or the "Constraint Validation API" solution, how do you make a select option required if it is contingent on another select field having a certain answer. I used the "required" method as you can see below which works great for Country select.
<select id="country_code" name="country_code" required>
<option value="">--None--</option>
<option value="AL">Albania</option>
<option value="US">United States</option>
</select>
<script>
$("select[name='country_code']").change(function() {
if ($(this).val() == "US") {
$("select[name='state_code'] option").removeClass('hidden');
$("select[name='state_code'] option").addClass('required');
} else {
} else {
$("select[name='state_code'] option").addClass('hidden');
}
});
</script>
<label for="state_code">State/Province</label>
<select id="state_code" name="state_code">
<option value="">--None--</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
</select>
As you can see, I tried adding the class "required" to State select if Country select is US, but it didn't do anything.

Jquery Conditional Statements for Multiple Checkbox Values

I'm new to posting/stackoverflow, so please forgive me for any faux pas. I have multiple buttons and checkboxes that I need to store the values of to place into conditional statements.
The HTML code:
<h1>SECTION 1: GENDER</h1>
<p>What is your gender?</p>
<input type="button" onclick="storeGender(this.value)" value="Male"/>
<input type="button" onclick="storeGender(this.value)" value="Female"/>
<hr />
<h1>SECTION 2: AGE</h1>
<p>What is your age?</p>
<input type="button" onclick="storeAge(this.value)" value="18–22"/>
<input type="button" onclick="storeAge(this.value)" value="23–30"/>
<hr />
<h1>SECTION 3: TRAITS</h1>
<h3>Choose Two:</h3>
<form>
<input name="field" type="checkbox" value="1"/> Casual <br />
<input name="field" type="checkbox" value="10"/> Cheerful <br />
<input name="field" type="checkbox" value="100"/> Confident <br />
<input name="field" type="checkbox" value="1000"/> Tough <br />
<input type="button" id="storeTraits" value="SUBMIT" /> <br />
</form>
<hr />
<h2>Here is what I suggest</h2>
<p id="feedback">Feedback goes here.</p>
jQuery code:
// set up variables
var gender;
var age;
var string;
$(document).ready(function() {
startGame();
$("#storeTraits").click( function() {
serializeCheckbox();
}
); }
);
function startGame() {
document.getElementById("feedback").innerHTML = "Answer all the questions.";
}
function storeGender(value) {
gender = value;
}
function storeAge(value) {
age = value;
}
function serializeCheckbox() {
// clear out any previous selections
string = [ ];
var inputs = document.getElementsByTagName('input');
for( var i = 0; i < inputs.length; i++ ) {
if(inputs[i].type == "checkbox" && inputs[i].name == "field") {
if(inputs[i].checked == true) {
string.push(inputs[i].value);
}
}
}
checkFeedback();
}
//Limit number of checkbox selections
$(function(){
var max = 2;
var checkboxes = $('input[type="checkbox"]');
checkboxes.change(function(){
var current = checkboxes.filter(':checked').length;
checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
});
});
function checkFeedback() {
if(gender == "Male") {
if (age == "18–22" && string == 11){
document.getElementById("feedback").innerHTML = "test1";
} else if (age == "18–22" && string == 110){
document.getElementById("feedback").innerHTML = "test2";
} else if (age == "18–22" && string == 1100){
document.getElementById("feedback").innerHTML = "test3";
} else if (age == "18–22" && string == 101){
document.getElementById("feedback").innerHTML = "test4";
}
}
}
I found this code on JSFiddle: http://jsfiddle.net/GNDAG/ which is what I want to do for adding together my trait values. However, when I try to incorporate it my conditional statements don't work. How do I add the code from the jsfiddle example and get the conditional statements to work? Thank you!
You need an integer, not a string array. Here's the code you need:
var traits = 0;
$('input[name=field]:checked').each(function () {
traits += parseInt($(this).val(), 10);
});
This will set the "traits" variable to an integer like 1, 11, 101, or 1001.
BTW: The second parameter to parseInt() is the base.
But a few suggestions:
Don't use "string" as a variable name.
Use radio buttons for gender and age.
Put all the input elements in the form.
Have one button that submits the form.
Attach a handler to the form submit event, and do your processing in that function, but call e.preventDefault() to prevent the form from submitting to the server. Alternatively, you could have the single button not be a submit button and attach an on-click handler to it.
Here's a jsfiddle with the code above and all the suggestions implemented.

Inline form Validation

I'm trying to get my form to validate inline but can't seem to get the right syntax, at the moment I have this, which does nothing yet. The first function, formhandler is meant to change the span elements text if the element gets blured and take away the error text once the field is focused at the moment it does neither of these.
<html>
<script type = "text/javascript">
document.getElementById("form").onfocus = function formHandler() {
for(var i = 0; i < document.getElementById("form").length; i+=1){
if(document.getElementById("form").elements[i].type == 'text') {
if(document.getElementById("form").elements[i].focus()) {
var onode = document.getElementById("form").elements[i].nextSibling;
onode.innerHTML = "";
valid = true;
}
else if(document.getElementById("form").elements[i].blur()) {
var onode = document.getElementById("form").elements[i].nextSibling;
onode.innerHTML = "Please Fill in Field";
valid = false;
}
}
}
}
function validate() {
var valid = false;
for(var i = 0; i < document.getElementById("form").length; i+=1){
if(document.getElementById("form").elements[i].type == 'text') {
if(document.getElementById("form").elements[i].value == "") {
var onode = document.getElementById("form").elements[i].nextSibling;
onode.innerHTML = "Please Fill in Field";
valid = true;
}
else{
var onode = document.getElementById("form").elements[i].nextSibling;
onode.innerHTML = "";
valid = false;
}
}
}
}
document.getElementById("form").onsubmit = validate;
</script>
<head>
<title>Question 1 / Vraag 1 - Basic JavaScript Validaton / Basiese JavaScript validasie
</title>
<link rel="Stylesheet" type="text/css" href="style.css" />
</head>
<body>
<form method="get" action="" id = "form">
<table>
<tr>
<td> Firstname:</td>
<td> <input type="text" name="firstname" id="firstname" /><span id="fnError">
</span></td>
</tr>
<tr>
<td> Surname:</td>
<td> <input type="text" name="surname" id="surname" /><span id="snError">
</span></td>
</tr>
<tr>
<td> Age:</td>
<td> <input type="text" name="age" id="age" /><span id="aError">
</span></td>
</tr>
<tr>
<td> Email:</td>
<td><input type="text" name="email" id="email" /><span id="eError">
</span></td>
</tr>
<tr><td colspan="2"><input type="button" value="Validate" onclick = "validate()"/></td></tr>
</table>
</form>
</body>
</html>
I'm trying to achieve this without the use of jquery, so please don't suggest it, thanks in advance.
These are problems I found in your code:
Line 1: Forms don't have a .focus method. What did you mean for that to do?
Line 2: Change .length to .elements:
for (var i = 0; i < document.getElementById("form").elements.length; i++ ) {
var node = document.getElementById("form").elements[i];
...
The elements in the form are now aliased as node.
Lines 4: The .focus/.blur method doesn't return true if the element is out of focus. We're going to have to do it ourselves:
node.onfocus = function() { this.isInFocus = true; };
node.onblur = function() { this.isBlurred = !this.isInFocus; };
The resulting code is as follows:
if ( node.isInfocus ) { ... }
else if ( node.isBlurred ) { ... }
Line 9: Refer to above.
Wrap the code in a window.onload to be able to use the DOM elements when the DOM has loaded.
This is your revised code; let me know if it works for you:
var nodes = document.getElementById('form').elements, node;
for ( var i = 0; i < nodes.length; i++ ) (function(i) {
nodes[i].onfocus = function() { this.isInFocus = true; };
nodes[i].onblur = function() { this.isBlurred = !this.isInFocus; };
})(i);
for (var i = 0; i < nodes.length; i++) {
node = nodes[i];
if (node.type == 'text') {
if (node.isInFocus) {
var onode = node.nextSibling;
onode.innerHTML = "";
valid = true;
} else if (node.isBlurred) {
var onode = node.nextSibling;
onode.innerHTML = "Please Fill in Field";
valid = false;
}
}
}
First major problem: you are trying to do all of this in the initial script load. The main DOM is not yet loaded at that time so document.getElementById("form") won't find anything. Do the function definitions in an onload handler.
Also, not sure what you are expecting "valid" to bind to in the first function. Finally, once you have determined validity or not, you need to do something with the result.
You are referencing dom elements which don't exist yet. One solution would be to move all your <script> tag before </body>, so elements exist when the script is executed.
Another way, with pure javascript would be to do this:
<script>
window.onload = function(){
//All your code here
}
</script>
(The validate function could be outside if you want)
Cheers

Categories