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.
Related
I am having troubles with a script with JS, I am still learning but I am stuck for a while.
The solution should be,
IF a checkbox is checked and the value is "" <-- the msgbox should say an message that the textbox should be filled with a value, and so for each checked checkbox, if you uncheck the checkbox, it should dissapear.
Code of 2 checkboxes in html page
<label>
bangkirai
<input id="chk_bangkirai" type="checkbox" onchange="enableTextBox()" />
</label>
<input type="text" id="bangkirai" name="bangkirai" disabled onchange="enableTextBox()" />
<label>
beukenhout
<input id="chk_beukenhout" type="checkbox" />
</label>
<input type="text" id="beukenhout" name="beukenhout" disabled/>
and the JavaScript, I made for each checkbox an other function, but I need to combine the error message in the same msgbox.
function enableTextBox() {
divOutput = document.getElementById("msgbox2");
strValideer = "<ul>";
if (document.getElementById("chk_bangkirai").checked === true) {
document.getElementById("bangkirai").disabled = false;
}
else {
document.getElementById("bangkirai").disabled = true;
}
if (document.getElementById("bangkirai").value === "") {
strValideer += "<li><b>bangkirai: </b>verplicht veld</li>";
}
strValideer += "</ul>";
divOutput.innerHTML = strValideer;
}
function enableTextBox2() {
divOutput = document.getElementById("msgbox2");
strValideer = "<ul>";
if (document.getElementById("chk_beukenhout").checked === true) {
document.getElementById("beukenhout").disabled = false;
}
else {
document.getElementById("beukenhout").disabled = true;
}
if (document.getElementById("beukenhout").value === "") {
strValideer += "<li><b>beukenhout: </b>verplicht veld</li>";
}
strValideer += "</ul>";
divOutput.innerHTML = strValideer;
}
I should probably use an array or an for each itteration ... but I can only find examples with forms ...
I will keep looking for a solution myself, but I hope I can get some inspiration here by experienced coders.
Thanks in advance
You could simplify this a lot and make it more... Concise and less dependent on which checkbox you have. We will do this with an external script and no onClick attributes on our HTML. This will enable us to separate our logic code from our design code. I will also use a placeholder instead of value, as it will create issues when people need to start entering a value (aka, you need to only have the text there when theres no value etc...) It just makes it more complicated.
Since we are dealing with numbers ('stuks' or amounts), lets also only allow number values to be inserted. Lastly, I have not bothered to replicate your HTML as I think the simplified example will make it easier to understand. Update I have also added the required and disabled sattributes here, settings your input to required when the checkbox is checked and disabled when not.
Check the below snippet for comments on the steps taken to do this:
// First, let select all fieldsets like this:
var fieldsets = document.querySelectorAll( 'fieldset.checkbox-message' );
// Lets loop through them
for( let i = 0; i < fieldsets.length; i++ ){
// Lets create variables to store our fieldset, checkbox and input for later use.
let fieldset = fieldsets[ i ];
let checkbox = fieldset.querySelector( 'input[type="checkbox"]' );
let input = fieldset.querySelector( 'input[type="number"]' );
// Lets also store the message we put in placeholder
// We will also give it a default value,
// in case you forget to set the placeholder.
let message = input.placeholder || 'Please fill in the amount';
// Now lets define a function that will fill the placeholder
// based on the checked value of the checkbox
// We will be storing it in a variable because of the scope of a `for` block.
// If you would use function setState() it might be defined globally
// So multiply checkboxes would not work.
let setState = function(){
if( checkbox.checked ){
input.placeholder = message;
input.disabled = false;
input.required = true;
} else {
input.placeholder = '';
input.disabled = true;
input.required = false;
}
}
// Now lets listen for changes to the checkbox and call our setState
checkbox.addEventListener( 'change', setState );
// Lrts also call setState once to initialise the correct placeholder
// for our input element to get started. This will remove any placeholders
// if the checkboxes are unchecked.
setState();
}
<fieldset class="checkbox-message">
<label for="bangkirai">Bangkirai</label>
<input type="checkbox" id="bangkirai" />
<input type="number" placeholder="Tell us, how many 'bangkirai'?" />
<span>stuks</span>
</fieldset>
<fieldset class="checkbox-message">
<label for="beukenhout">Beukenhout</label>
<input type="checkbox" id="beukenhout" />
<input type="number" placeholder="How many 'beukenhout'?" />
<span>stuks</span>
</fieldset>
Good luck coding!
#somethinghere's answer is concise but if we modify your answer as it is you could check this
function enableTextBox() {
bangkirai_validation = document.getElementById("bangkirai_validation");
if (document.getElementById("chk_bangkirai").checked === true) {
document.getElementById("bangkirai").disabled = false;
}
else {
document.getElementById("bangkirai").disabled = true;
bangkirai_validation.style.display='none';
return;
}
if (document.getElementById("bangkirai").value =="") {
bangkirai_validation.style.display='block';
}else
{
bangkirai_validation.style.display='none';
}
}
function enableTextBox2() {
beukenhout_validation = document.getElementById("beukenhout_validation");
if (document.getElementById("chk_beukenhout").checked === true) {
document.getElementById("beukenhout").disabled = false;
}
else {
document.getElementById("beukenhout").disabled = true;
beukenhout_validation.style.display='none';
return;
}
if (document.getElementById("beukenhout").value == "") {
beukenhout_validation.style.display='block';
}else
{
beukenhout_validation.style.display='none';
}
}
<fieldset>
<legend>Bestel gegevens</legend>
<div class="container">
<div class="row">
<div class="span7 id=" houtsoorten"">
<div class="control-group">
<label class="control-label">
bangkirai
<input id="chk_bangkirai" type="checkbox"
onchange="enableTextBox()" >
</label>
<div class="controls">
<div class="input-append">
<input class="inpbox input-mini"
type="number" id="bangkirai" name="bangkirai" placeholder="aantal" disabled
onkeyup="enableTextBox()" onchange="enableTextBox()">
<span class="add-on">stuks</span>
<div style="display:none;" id="bangkirai_validation">Please enter a value</div>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">
beukenhout
<input id="chk_beukenhout" type="checkbox" onchange="enableTextBox2()" >
</label>
<div class="controls">
<div class="input-append">
<input class="inpbox input-mini"
type="number" id="beukenhout" name="beukenhout" placeholder="aantal"
disabled onkeyup="enableTextBox2()" onchange="enableTextBox2()" >
<span class="add-on">stuks</span>
<div style="display:none;" id="beukenhout_validation">Please enter a value</div>
</div>
</div>
</div>
In a js code, i created 3 buttons --- button 1...button 2...button 3
and 3 input fields --- input field 1...input field 2...input field 3
From the beginning of the script all buttons are disabled
button 1 will only be activated (you can click on it) when input field 1 and 2 have numerated values
button 2 will only be activated when input field 1 and 3 have numerated values
button 3 will only be activated when input field 2 and 3 have numerated values.
My problem is when i entered a numerated value for input field 1 and 2, button 1 will not activate (in-clickable) even though it was suppose to
And lets say i redid my code and got my whole code backwards so, at the beginning of my script all the buttons were not disabled (you could click on them). Then i made a simple conditional statement like so
input field 1 = if1
input field 2 - if2
if (if1.length = 0 || isNaN(if1) && if2.length = 0 || isNaN(if2) ) {
document.getElementById("button 1").disable = true;
}
Button 1 will not immediately disable until the user clicks on the button. And if the user were to re-enter the appropriate value type in input field 1, button 1 will not activate (be-clickable) because apparently its permanently disabled.
So down to summary, I'm asking if there is a way to make JavaScript be instantly interactive. Such as a web browser search bar. The moment you type something, you immediately get a list of possible questions and when you don't type anything in them the list disappears and the browser regains its original state.
Any Advice/help shall be greatly appreciated
Due to Life and its problems my code some how got deleted. Thus the lack of code and bunch of words. Sorry.
Generic solution (using attributes)
You can check the answer below which is using oninput event and the attributes to handle your situation effectively.
I have added a data-target attribute to link the elements together to fit with your requirement.
For an instance, to match the rule button 1 will only be activated (you can click on it) when input field 1 and 2 have numerated values, data-target of button1 is id of textbox 1 & 2.
Working snippet:
function checkInput() {
var dataTarget = 'data-target';
var elm = event.target;
var targetAttrs = getAttr(elm, dataTarget);
if(targetAttrs) {
var targetButtons = targetAttrs.split(',');
for(var i = 0; i < targetButtons.length; i++) {
var button = document.getElementById(targetButtons[i]);
targetAttrs = getAttr(button, dataTarget);
if(targetAttrs) {
var targetTextBoxes = targetAttrs.split(',');
var valid = true;
for(var j = 0; j < targetTextBoxes.length; j++) {
var textBox = document.getElementById(targetTextBoxes[j]);
if(textBox) {
valid = isValidNumber(textBox.value);
}
if(!valid) {
break;
}
}
button.disabled = !valid;
}
}
}
}
function isValidNumber(val) {
return (val && val.length > 0 && !isNaN(val));
}
function getAttr(elm, name){
var val;
if(elm) {
var attrs = elm.attributes;
for(var i = 0; i < attrs.length; i++) {
if(attrs[i].name === name) {
val = attrs[i].value;
break;
}
}
}
return val;
}
<div>
<input type="text" id="textBox1" oninput="checkInput()" data-target="button1,button2" />
</div>
<br/>
<div>
<input type="text" id="textBox2" oninput="checkInput()" data-target="button1,button3" />
</div>
<br/>
<div>
<input type="text" id="textBox3" oninput="checkInput()" data-target="button2,button3" />
</div>
<br/>
<input type="button" id="button1" value="Submit" data-target="textBox1,textBox2" disabled />
<input type="button" id="button2" value="Submit" data-target="textBox1,textBox3" disabled />
<input type="button" id="button3" value="Submit" data-target="textBox2,textBox3" disabled />
Note: With this code, when you add more elements, you don't need to change/add any Javascript code. Just add the elements and attributes
var field1 = document.getElementById('if1');
var field2 = document.getElementById('if2');
var field3 = document.getElementById('if3');
var button1 = document.getElementById('button1');
var button2 = document.getElementById('button2');
var button3 = document.getElementById('button3');
field1.addEventListener('input', function(){
if(this.value!= '' && field2.value!='')
button1.disabled = false;
else
button1.disabled = true;
if(this.value!= '' && field3.value!='')
button2.disabled = false;
else
button2.disabled = true;
});
field2.addEventListener('input', function(){
if(this.value!= '' && field1.value!='')
button1.disabled = false;
else
button1.disabled = true;
if(this.value!= '' && field3.value!='')
button3.disabled = false;
else
button3.disabled = true;
});
field3.addEventListener('input', function(){
if(this.value!= '' && field1.value!='')
button2.disabled = false;
else
button2.disabled = true;
if(this.value!= '' && field2.value!='')
button3.disabled = false;
else
button3.disabled = true;
});
<input type="text" id="if1">
<input type="text" id="if2">
<input type="text" id="if3">
<br>
<button type="button" id="button1" disabled="true">Button1</button>
<button type="button" id="button2" disabled="true">Button2</button>
<button type="button" id="button3" disabled="true">Button3</button>
Here is how you do it
Disabling a html button
document.getElementById("Button").disabled = true;
Enabling a html button
document.getElementById("Button").disabled = false;
Demo Here
Edited
Try this...
You apply addEventListener to that DOM object:
document.getElementById("IDTeam").addEventListener("change", function() {//call function here});
For IE
document.getElementById("IDTeam").attachEvent("onchange", function() {//call function here} );
I have a form that the user can use to enter 5 numbers. I have given all five input boxes the same id and a different name. I want to perform a validation of each input box. I want to be able to change background color of the input boxes based on the number they enter. For example, every input box with number in range 0-5 should change its background color to red and those between 6-10 should be green.
I have been able to write a code that would cause the color to change for one input box, however I cannot think of a way to optimize my code and avoid having to write the same code five times. Here is what I have got so far:
Form:
<form id="numbers">
Number1: <input id ="color" name="num1" type="number" onchange="check();">
<br><br>
Number2: <input id ="color" name="num2" type="number" onchange="check();">
<br><br>
Number3: <input id ="color" name="num3" type="number" onchange="check();">
<br><br>
</form>
Function:
function check() {
var inputVal = document.getElementById("color").value;
if (inputVal=="" || inputVal ==null) {
document.getElementById("color").style.backgroundColor = "white";
}
else if (inputVal >= 0 && inputVal <= 5) {
document.getElementById("color").style.backgroundColor = "red";
}
else if (inputVal >= 6 && inputVal <= 10) {
document.getElementById("color").style.backgroundColor = "green";
}
}
If I change inputVal to an array and use a for loop to save values of document.getElementById("color").value, it will save the first number entered by the user five times and will only update the color of the first box.
Here is what I tried:
var inputVal = new Array();
for(var i=0; i<5; i++) {
inputVal[i]= document.getElementById("color").value;
}
You can have the clicked element as a parameter
function check(element) {
var inputVal = element.value;
if (inputVal=="" || inputVal ==null) {
element.style.backgroundColor = "white";
}
else if (inputVal >= 0 && inputVal <= 5) {
element.style.backgroundColor = "red";
}
else if (inputVal >= 6 && inputVal <= 10) {
element.style.backgroundColor = "green";
}
}
and pass the argument for each input
<form id="numbers">
Number1: <input id ="color1" name="num1" type="number" onchange="check(this);" />
<br/><br/>
Number2: <input id ="color2" name="num2" type="number" onchange="check(this);" />
<br/><br/>
Number3: <input id ="color3" name="num3" type="number" onchange="check(this);" />
<br/><br/>
</form>
But ID's must be unique. Here is a FIDDLE
You can use jquery to achieve this. First remove all the id value, they should not be same. Then use $('input').on('change', function (){
$(this).css("background-color","red")})...
This way you can change colors based on values.
First, you can simplify your JavaScript by designating it to target this, since you're executing the function onchange.
Second, you should never leave an open-ended IF...THEN...ELSE, just bad habit for when they can result in BIG changes.
Third, as noted by others, id must be unique across the page.
Give this a try:
function check(tar) {
var inputVal = tar.value;
if(inputVal == '' || inputVal == null) {
tar.style.backgroundColor = 'white';
} else if(inputVal >= 0 && inputVal <= 5) {
tar.style.backgroundColor = 'red';
} else if(inputVal >= 6 && inputVal <= 10) {
tar.style.backgroundColor = 'green';
} else {
tar.style.backgroundColor = 'yellow';
}
}
<form id="numbers">
Number1: <input class ="color" name="num1" type="number" onchange="check(this);" />
<br><br>
Number2: <input class ="color" name="num2" type="number" onchange="check(this);" />
<br><br>
Number3: <input class ="color" name="num3" type="number" onchange="check(this);" />
</form>
Here's a JSFiddle: http://jsfiddle.net/v1daq6sx/
I hope this helps. ^^
When the user changes their value it fires the function giveInputColor. You can use this one function to check infinitely many inputs with the class hello.
Working Example: http://codepen.io/anon/pen/bNqraN
HTML
<input class="hello"/>
<input class="hello"/>
<input class="hello"/>
<input class="hello"/>
<input class="hello"/>
jQuery
$('input.hello').keyup(function(event) {
/* Act on the event */
var value = $(this).val();
$(this).css('backgroundColor', giveInputColor(value));
});
function giveInputColor(value) {
// Give Input a color based on value parameter
if (value >= 0 && value <= 5) return 'Red';
else if (value >= 6 && value <= 10) return 'Green';
else return 'White';
}
Without going into any major redesign of your logic (you could make it more efficient, but I focused on just getting the behavior that you are looking for), you can simply add the function to each element with an event listner, and then use e.target to determine which element is the one that changed and triggered the function call. Note - the aproach is a little more streamlined in jQuery, but I will stick with native JS here.
First off, lets give all of these inputs a common class ("number-field"), to make them easier to find:
<form id="numbers">
Number1: <input id="num1" name="num1" type="number" class="number-field">
<br><br>
Number2: <input id="num2" name="num2" type="number" class="number-field">
<br><br>
Number3: <input id="num3" name="num3" type="number" class="number-field">
<br><br>
</form>
I also made the id attributes unique and remover the onchange attributes, since we whill add the event listener dynamically.
Then we needed updated the check() function to accept the change event as a parameter (e) which is used in the first line of the function to determine the element that triggered the change event, using e.target (note - e.srcElement is to support older versions of IE).
function check(e) {
var inputEl = e.target || e.srcElement;
var inputVal = inputEl.value;
if (inputVal == "" || inputVal == null) {
this.style.backgroundColor = "white";
}
else if (inputVal >= 0 && inputVal <= 5) {
this.style.backgroundColor = "red";
}
else if (inputVal >= 6 && inputVal <= 10) {
this.style.backgroundColor = "green";
}
}
The rest of the code is simply updated to point to the variable that was determined in the first line.
Finally, the function needed to be bound to the number inputs, so, using the class attribute that I added earlier, you can find all of those inputs, cycle through them, and add event listeners to each one.
var numInputs = document.getElementsByClassName("number-field");
for (i = 0; i < numInputs.length; i++) {
numInputs[i].addEventListener('change', check);
}
I checked it out locally and it is behaving the way that I believe that you were wanting it to.
In a part of my application where i check for duplicate radio input selection and revert if its already selected to early selection.
Here is my html code ..
<input type="radio" name="A" checked="checked" onclick="return check();" />
<input type="radio" name="A" onclick="return check();" />
<br />
<input type="radio" name="B" onclick="return check();" />
<input type="radio" name="B" checked="checked" onclick="return check();" />
Here is the javascript code
function check() {
//logic to check for duplicate selection
alert('Its already selected');
return false;
}
And here is the demo
The above code works fine. The issue is when the input isn't initially checked. In such condition the radio input selection doesn't revert to unchecked.
NOTE: when in checked state, returning false shows and alert and sets the check box to initial checked state. But when initially in non checked state this doesn't work.
In DOM ready, check if any radio button is checked or not. If any radio button is checked, increase the counter by one. In onclick of the radio button, check if the counter value is 1. if yes, return false, else increase counter by 1.
try this code,
html
<input type="radio" name="A" checked="checked" />
<input type="radio" name="A" />
<br />
<input type="radio" name="B" />
<input type="radio" name="B" />
JS
var counterA = 0;
var counterB = 0;
$(document).ready(function () {
if ($("input:radio[name=A]").is(":checked") == true) counterA++;
if ($("input:radio[name='B']").is(":checked") == true) counterB++;
});
$('input:radio[name=A]').click(function () {
if (counterA == 1) {
alert('already checked');
return false;
} else {
counterA++;
}
});
$('input:radio[name=B]').click(function () {
if (counterB == 1) {
alert('already checked');
return false;
} else {
counterB++;
}
});
SEE THIS DEMO
iJay wants to ask several questions and privides the same answers for each question. Each answer can only be choosen once. If a user clicks the same answer the second time a error-message should be shown.
// get all elements
var elements = document.querySelectorAll('input[type="radio"]');
/**
* check if radio with own name is already selected
* if so return false
*/
function check(){
var selected_name = this.name,
selected_value = this.value,
is_valid = true;
// compare with all other elements
for(var j = 0; j < len; j++) {
var el = elements[j];
// does the elemenet have the same name AND is already selected?
if(el.name != selected_name && el.value == selected_value && el.checked){
// if so, selection is not valid anymore
alert('Oups..! You can not select this answer a second time :( Choose another one!')
// check current group for previous selection
is_valid = false;
break;
}
};
return is_valid;
}
/**
* bind your elements to the check-routine
*/
for(var i = 0, len = elements.length; i < len; i++) {
elements[i].onmousedown = check;
}
Here is a DEMO
Use $yourRadio.prop('checked', false); to uncheck the specific radio.
Use like this:
function check() {
//logic to check for duplicate selection
var checked = true ? false : true;
$(this).prop('checked', checked);
return false;
}
1) add class attribute to same type of checkbox elements(which are having same name)
ex: class = "partyA"
2)
var sourceIdsArr = new Array();
function check() {
$('.partyA').each(function() {
var sourceId = $(this).val();
if(sourceIdsArr.indexOf(sourceId) != -1){
sourceIdsArr.push(sourceId );
}
else{
alert('Its already selected');
return false;
}
});
}
Here is your code..
function check() {
//logic to check for duplicate selection
var selectflag=0;
var radiovalue=document.getElementsByName("B");
for(var i=0;i<radiovalue.length;i++)
{
// alert(radiovalue[i].checked);
if(radiovalue[i].checked==true)
{
selectflag=1;
break;
}
}
if(selectflag==1)
{
alert('Its already selected');
return false;
}
return true;
}
Trigger your event on MouseDown. It will work fine.
I think this is something you are looking for :
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<input type="radio" name="A" checked="checked" onclick="return check(this);"/>
<input type="radio" name="A" onclick="return check(this);"/>
<script>
$( document ).ready(function() {
this.currentradio = $("input[name='A']:checked")[0];
});
function check(t) {
var newradio= $("input[name='A']:checked")[0];
if (newradio===document.currentradio){
alert('already selected');
return false
}else{
document.currentradio = $("input[name='A']:checked")[0];
}
}
</script>
</body>
<html>
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)