JavaScript Giving 'Object Expected' Error - javascript

I am writing some code that shows or hides a calendar based on a drop down select form. I have it set to run my showHideCalendar() function as an onchange action on the drop down selection. When I change the selected option I receive an "Object expected" error. I have included the relevant HTML and JavaScript code.
<script type="text/javascript" language="javascript">
function showHideCalendar(element) {
document.getElementById("calendar").style.display = "none";
if (document.getElementById("dropdown").selectedIndex === 13) {
cal5.popup();
document.getElementById("textField").value = "";
document.getElementById("calendar").style.display = "inline";
}
}
</script>
<FORM NAME='Labs' METHOD='POST' ACTION="">
<select id="dropdown" name='TimeFrame0' onchange='showHideCalendar(document.Labs.TimeFrame0)'>
<option value='NoReorder'>Do Not Reorder</option>
<option value='2012-06-14 08:40:39.067'>Today</option>
<option value='2012-06-21 08:40:39.067'>1 Week</option>
<option value='2012-06-28 08:40:39.067'>2 Weeks</option>
<option value='2012-07-05 08:40:39.067'>3 Weeks</option>
<option value='2012-07-12 08:40:39.067'>4 Weeks</option>
<option value='2012-07-26 08:40:39.067'>6 Weeks</option>
<option value='2012-07-14 08:40:39.067' selected>1 Month</option>
<option value='2012-08-14 08:40:39.067'>2 Months</option>
<option value='2012-09-14 08:40:39.067'>3 Months</option>
<option value='2012-10-14 08:40:39.067'>4 Months</option>
<option value='2012-12-14 08:40:39.067'>6 Months</option>
<option value='2013-03-14 08:40:39.067'>9 Months</option>
<option value='custom' id='custom'>Calendar Select</option>
</select>
<div id='calendar' style='display:inline'>
<input type=text name='StartDate' value='' size=20 onchange='inputChanged()' onkeydown='inputChanged()' onblur='inputChanged()' id='textField'>
<a href='javascript:cal5.popup();' onmousedown='inputChanged()'> <img src='/jscalendar/img/cal.gif' width='16' height='16' border='0' alt='Click Here to Pick up the date'></a>
</div>
<input type=checkbox name=SameDate value='on' checked onClick='SetTimeFrame(document.Labs.TimeFrame0)'> Use Same Date For All Labs
<input class='btnsave' type=button name=Save value='Reorder Labs' onClick=javascript:document.Labs.action='/LabReview/Reorder.php?PROV=PROVID&MaxCount=2&Text=1';document.Labs.submit();>
<input class='btncancel' type=button name=Cancel value=Cancel onClick=javascript:top.window.close()>
</FORM>
Does anyone see any reason why this is not working. The error is thrown on the line <select id="dropdown" name='TimeFrame0' onchange='showHideCalendar(document.Labs.TimeFrame0)'>.
One of the answerers thinks the error isn't in my new code, but rather something else on the page. I am editing my question to add the rest of the javascript that is on the page.
<script type="text/javascript" language="javascript">
function showHideCalendar(element) {
document.getElementById("calendar").style.display = "none";
if (document.getElementById("dropdown").selectedIndex === 13) {
cal5.popup();
document.getElementById("textField").value = "";
document.getElementById("calendar").style.display = "inline";
}
}
function inputChanged() {
document.getElementById("dropdown").selectedIndex = 13;
}
function SetTimeFrame(element)
{
if (document.Labs.SameDate.checked==true)
{
var Elements=document.Labs.elements.length;
for (var i=0; i<Elements; i++)
{
if (document.Labs.elements[i].type=='select-one')
{
document.Labs.elements[i].options[element.selectedIndex].selected=true;
}
}
}
}
if (top.window.opener.document.getElementById("Complete<?php echo($_GET['Item']); ?>"))
{
if ('<?php echo($Reviewed); ?>' == 'yes')
{
window.opener.document.getElementById("Complete<?php echo($_GET['Item']); ?>").style.visibility='visible';
window.opener.document.getElementById("Partial<?php echo($_GET['Item']); ?>").style.visibility='hidden';
}
else if ('<?php echo($Reviewed); ?>' == 'partial')
{
window.opener.document.getElementById("Partial<?php echo($_GET['Item']); ?>").style.visibility='visible';
window.opener.document.getElementById("Complete<?php echo($_GET['Item']); ?>").style.visibility='hidden';
}
}
else
{
var temp=top.window.opener.location.href;
top.window.opener.location.href=temp;
top.window.opener.top.window.location.reload();
}
function DateCheck(element)
{
var xx = element.value;
var re = new RegExp("^[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]$");
var re2 = new RegExp("^[0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]$");
var re3 = new RegExp("^[0-9][0-9]/[0-9]/[0-9][0-9][0-9][0-9]$");
var re4 = new RegExp("^[0-9]/[0-9]/[0-9][0-9][0-9][0-9]$");
var error = "";
var maxdays = new Array(0,31,29,31,30,31,30,31,31,30,31,30,31);
var retval = true;
if(element.value != "")
{
if(xx.search(re) < 0 && xx.search(re2) < 0 && xx.search(re3) < 0 && xx.search(re4) < 0)
{
error = "Invalid Date Format " + xx + ". Please enter dates in the format mm/dd/yyyy."
retval = false;
element.value = ""
}
else
{
var list = xx.split("/");
var month = list[0];
if(month.charAt(0) == "0")
month = month.substr(1);
if( list[0] < 1 || list[0] > 12)
{
error = "Invalid Month " + list[0];
retval = false;
element.value = ""
}
else
if(list[1] < 1 || list[1] > maxdays[month])
{
error = "Invalid Day " + list[1];
retval = false;
element.value = ""
}
else
if(list[2] < 1900)
{
error = "Invalid Year (Must be greater than 1900) " + list[2];
retval = false;
element.value = ""
}
}
if(!retval)
alert(error);
return retval;
}
}
</script>

Change:
<select id="dropdown" name='TimeFrame0' onchange='showHideCalendar(document.Labs.TimeFrame0)'>
To:
<select id="dropdown" name='TimeFrame0' onchange='showHideCalendar(this)'>

It turns out the problem was caused by the following block of code.
if (top.window.opener.document.getElementById("Complete<?php echo($_GET['Item']); ?>")) {
if ('<?php echo($Reviewed); ?>' == 'yes')
{
window.opener.document.getElementById("Complete<?php echo($_GET['Item']); ?>").style.visibility='visible';
window.opener.document.getElementById("Partial<?php echo($_GET['Item']); ?>").style.visibility='hidden';
}
else if ('<?php echo($Reviewed); ?>' == 'partial')
{
window.opener.document.getElementById("Partial<?php echo($_GET['Item']); ?>").style.visibility='visible';
window.opener.document.getElementById("Complete<?php echo($_GET['Item']); ?>").style.visibility='hidden';
}
}
else
{
var temp=top.window.opener.location.href;
top.window.opener.location.href=temp;
top.window.opener.top.window.location.reload();
}
When I removed that from the code, it worked like a charm. Thanks to everyone for their suggestions and thoughts.

Related

how to fix jquery error TypeError: 'click' called

I'm working on a project which is a control panel for minecraft servers, this is the configuration section in this and created a form that the user must complete to make the configuration and to send the values ​​eh used ajax but I get this error : TypeError: 'click' called on an object that does not implement interface HTMLElement.
How can I solve that
I speak Spanish so the document is in Spanish
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<?php
$file = "../home/server.properties";
if (file_exists($file)) {
$file = file("../home/server.properties");
if (!str_replace("allow-flight=false", "allow-flight=false", $file)) {
$fly = "true";
} else {
$fly = "false";
}
if (!str_replace("force-gamemode=false", "force-gamemode=false", $file)) {
$forgm = "true";
} else {
$forgm = "false";
}
if (str_replace("spawn-npcs=false", "spawn-npcs=false", $file) == true) {
$NPCS = "true";
} else {
$NPCS = "false";
}
if (str_replace("spawn-animals=false", "spawn-animals=false", $file) == true) {
$animal = "true";
} else {
$animal = "false";
}
if (str_replace("online-mode=true", "online-mode=true", $file) == true) {
$pirate = "false";
} else {
$pirate = "true";
}
$file2 = implode('|',$file);
if (strpos($file2, "pvp=true") == true) {
$pvp = "true";
} else {
$pvp = "false";
}
if (strpos($file2, "difficulty=0") == true) {
$diff = 0;
}
if (strpos($file2, "difficulty=1") == true) {
$diff = 1;
}
if (strpos($file2, "difficulty=2") == true) {
$diff = 2;
}
if (strpos($file2, "difficulty=3") == true) {
$diff = 3;
}
if (strpos($file2, "enable-command-block=true") == true) {
$command_block = "true";
} else {
$command_block = "false";
}
if (strpos($file2, "gamemode=0") == true) {
$gm = 0;
}
if (strpos($file2, "gamemode=1") == true) {
$gm = 1;
}
if (strpos($file2, "gamemode=2") == true) {
$gm = 2;
}
if (strpos($file2, "spawn-monsters=true") == true) {
$criaturas = "true";
} else {
$criaturas = "false";
}
if (file_exists("../motd12.save")) {
$save1 = file("../motd12.save");
$save1 = implode('|',$save1);
$save1 = base64_decode($save1);
$motd = $save1;
$not_exists = 0;
} else {
$not_exists = 1;
$motd = "A Minecraft Server";
}
$svp = 1;
} else {
$svp = 0;
}
$js = 'var valuesL = ["'.$fly.'","'.$forgm.'","'.$NPCS.'","'.$animal.'","'.$pirate.'","'.$pvp .'","'.$diff.'","'.$command_block.'","'.$gm.'","'.$criaturas.'","'.$motd.'"];';
?>
<?php
echo "<script>";
echo $js;
echo 'var svp = "'.$svp.'"';
echo "</script>";
?>
<meta charset="UTF-8">
<title>Panel de Control ° Config</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<link rel="stylesheet" href="../Css/estilos.css">
<link rel="stylesheet" href="../demo-files/demo.css">
<link rel="stylesheet" href="../console/static/css/bootstrap.min.css">
</head>
<body>
<div class="nav_bar">
<div class="content">
General
Configuración
Plugins / Mods
Log
</div>
</div>
<div class="panel-control">
<span class="titulo-text">Configuraciones </span>
<div class="comp">
<div class="save-config">
Permitir volar: <select name="fly" id="fly">
<option value="true">Si</option>
<option value="false">No</option>
</select>
<br>
Forzar modo de juego: <select name="forgm" id="forgm">
<option value="true">Si</option>
<option value="false">No</option>
</select>
<br>
Spawnear NPCS:
<select name="npcs" id="npcs">
<option value="true">Si</option>
<option value="false">No</option>
</select>
<br>
Spawnear animales:
<select name="animal" id="animal">
<option value="true">Si</option>
<option value="false">No</option>
</select>
<br>
Permitir minecraft pirata:
<select name="pirate" id="pirate">
<option value="true">Si</option>
<option value="false">No</option>
</select>
<br>
Jugador contra jugador:
<select name="pvp" id="pvp">
<option value="true">Si</option>
<option value="false">No</option>
</select>
<br>
Dificultad:
<select name="dificulty" id="dificulty">
<option value="pacifico">Pacifico</option>
<option value="facil">Facil</option>
<option value="normal">Normal</option>
<option value="hard">Dificil</option>
</select>
<br>
Permitir bloque de commandos:
<select name="command_block" id="command_block">
<option value="true">Si</option>
<option value="false">No</option>
</select>
<br>
Modo de juego:
<select name="npcs" id="npcs">
<option value="survival">Survival</option>
<option value="creativo">Creativo</option>
<option value="aventura">Aventura</option>
</select>
<br>
Generar Criaturas:
<select name="criaturas" id="criaturas">
<option value="true">Si</option>
<option value="false">No</option>
</select>
<br>
MOTD:
<input type="text" id="motd" name="motd" placeholder="Motd del server">
<br>
<span class="respuesta"></span>
<br>
<button class="btn-submit" onclick="mifuncionchingona()" id="btn-submit">Save</button>
</div>
</div>
</div>
</body>
<script>
var dificultades = ["pacifico","facil","normal","hard"];
var gamemodes = ["survival","creativo","aventura"];
$(document).ready(function() {
loadnames();
});
// funciones //
function loadnames() {
$('#fly').val(valuesL[0]);
$('#forgm').val(valuesL[1]);
$('#npcs').val(valuesL[2]);
$('#animal').val(valuesL[3]);
$('#pirate').val(valuesL[4]);
$('#pvp').val(valuesL[5]);
$('#dificulty').val(dificultades[valuesL[6]]);
$('#command_block').val(valuesL[7]);
$('#gm').val(gamemodes[valuesL[8]]);
$('#criaturas').val(valuesL[9]);
$('#motd').val(valuesL[10]);
}
$.get("stat.php", function(data,status) {
$('#result').html(data);
if (data == "Detenido") {
var status = "detenido";
} else {
var status = "enlinea";
}
});
function mifuncionchingona() {
var fly = $('#fly').val(),
forgm = $('#forgm').val(),
npcs = $('#npcs').val(),
animal = $('#animal').val(),
piratas = $('#pirate').val(),
pvp = $('#pvp').val(),
difficulty = $('#dificulty').val(),
command_block = $('#command_block').val(),
gm = $('#gm').val(),
criaturas = $('#criaturas').val(),
motd = $('#motd').val();
var values = [fly,forgm,npcs,animal,piratas,pvp,dificulty,command_block,gm,criaturas,motd];
if (status == "enlinea") {
$.get('../stop.php', function(data) {
});
$.post('save.php', {
"fly":values[0],
"forgm":values[1],
"npcs":values[2],
"animal":values[3],
"piratas":values[4],
"pvp":values[5],
"diff":values[6],
"command_block":values[7],
"gm":values[8],
"criaturas":values[9],
"motd":values[10]
}, function(data, status) {
console.log("Esperando "+data);
$('.respuesta').html('Los cambios se an realizado con exito, el server se esta reiniciando!');
});
} else {
$.post('save.php', {
"fly":values[0],
"forgm":values[1],
"npcs":values[2],
"animal":values[3],
"piratas":values[4],
"pvp":values[5],
"diff":values[6],
"command_block":values[7],
"gm":values[8],
"criaturas":values[9],
"motd":values[10]
}, function(data, status) {
console.log("Esperando "+data);
$('.respuesta').html('Los cambios se an realizado con exito!');
});
}
}
</script>
</html>
In the line
var values = [fly,forgm,npcs,animal,piratas,pvp,dificulty,command_block,gm,criaturas,motd];
the variable dificulty doesn't exist (is misspelled). This may be cascading and causing your error.

Default value not working in select tag if the user doesn't select any options?

Hello,
I'm trying to make a default value of language selection to be English whose value is 1. So if the user doesn't select language option, it should still be 1 so that I can run my algorithm. But when I test it that doesn't select any value, it doesn't make it default value.
And I decided to check the datatype of language option, it's a string type, but even if I make if(isNaN(languageOption)){ languageOption = "1";}, it's still not working. Can anyone tell me why?
Thank you for your help
<body>
<div>
<img src="image/MindScribe-cursive.png" id="cursive">
</div>
<div id="container">
<img src="image/MindScribe-zebra.png" id="ImageEnterVariables" alt="Hello, I'm Stripes">
<img src="image/MindScribe-zebra2.png" id="onlyShowZebraImage" alt="Hello, I'm Stripes" style=display:none>
<select id="languageSelection" style=display:none>
<option value="">Choose a language</option>
<option value="1">English (American)</option>
<option value="2">Chinese (Mandarin)</option>
<option value="3">Japanese</option>
</select>
<script>
var languageOption = parseInt($("#languageSelection").val() );
$("#languageSelection").on("change", function(){
if(isNaN(languageOption)){ languageOption = "1";}
languageOption = $(this).val();
console.log("langugeOption is " + languageOption);
console.log("Language changed to: "+ $(this).find("option").eq( $(this)[0].selectedIndex ).text() + " (Index: "+languageOption+")" );
console.log(typeof(languageOption)); // Outputs string
endingArr = [];
runThroughArr = [];
randomArr = [];
if(languageOption === "1"){
console.log("English");
for(i = 0; i < intro_playList.length; i++){
if(intro_playList[i].stage === "ending"){ endingArr.push(i); }
if(intro_playList[i].runThrough){ runThroughArr.push(i); }
if(intro_playList[i].random){ randomArr.push(i); }
}
}
else if (languageOption === "2"){
console.log("Chinese");
for(i = 0; i < intro_playList_chi.length; i++){
if(intro_playList_chi[i].stage === "ending"){ endingArr.push(i); }
if(intro_playList_chi[i].runThrough){ runThroughArr.push(i); }
if(intro_playList_chi[i].random){ randomArr.push(i); }
}
}
});
</script>
</body>
Why you are doing these much stuff for making English default value? You can just add selected attribute to that option which you want to make default.
<select id="languageSelection" style=display:none>
<option value="">Choose a language</option>
<option value="1" selected>English (American)</option>
<option value="2">Chinese (Mandarin)</option>
<option value="3">Japanese</option>
</select>
And in your script, you can apply below logic to set default option to 1 :
languageOption = $(this).val();
if(languageOption==""){
languageOption="1";
}
$("#languageSelection").on("change", function(){
var languageOption = $(this).val();
if(languageOption.length==0){
languageOption=1;
}
console.log("langugeOption is " + languageOption);
console.log("Language changed to: "+ $(this).find("option").eq( $(this)[0].selectedIndex ).text() + " (Index: "+languageOption+")" );
console.log(typeof(languageOption)); // Outputs string
endingArr = [];
runThroughArr = [];
randomArr = [];
if(languageOption === "1"){
console.log("English");
for(i = 0; i < intro_playList.length; i++){
if(intro_playList[i].stage === "ending"){ endingArr.push(i); }
if(intro_playList[i].runThrough){ runThroughArr.push(i); }
if(intro_playList[i].random){ randomArr.push(i); }
}
}
else if (languageOption === "2"){
console.log("Chinese");
for(i = 0; i < intro_playList_chi.length; i++){
if(intro_playList_chi[i].stage === "ending"){ endingArr.push(i); }
if(intro_playList_chi[i].runThrough){ runThroughArr.push(i); }
if(intro_playList_chi[i].random){ randomArr.push(i); }
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="languageSelection" >
<option value="">Choose a language</option>
<option value="1">English (American)</option>
<option value="2">Chinese (Mandarin)</option>
<option value="3">Japanese</option>
</select>
Above code works for me, it gives me 1 if Choose a language is selected.
If you need the "Choose a language" to be displayed, set its value to 1 (the same as English):
<option value="1">Choose a language</option>

Show fields(textbox and labels) based on value from dropdown list

I have a dropdown with a selected value by default. My idea is to load the fields when that value is on the default selected. How do I make that? I'm trying to use onload on the div but I have little knowledge in javascript.
Here is my javascript code
function check()
{
$(document).ready(function()
{
if($('#status').val() == 'Cancelled' || $('#status').val() == 'Hold')
{
$('#prf').show();
$('#lblreason').show();
$('#lbldate').show();
$('#reason').show();
$('#date').show();
if($('#status').val() == 'Cancelled')
{
document.getElementById("lblreason").innerHTML = "Cancellation Reason";
document.getElementById("lbldate").innerHTML = "Date of Cancellation";
}
if($('#status').val() == 'Hold')
{
document.getElementById("lblreason").innerHTML = "Hold Reason";
document.getElementById("lbldate").innerHTML = "Date of Hold";
}
}
else
{
$('#prf').hide();
$('#lblreason').hide();
$('#lbldate').hide();
$('#reason').hide();
$('#date').hide();
}
}
}
HTML
<div id = "prf" onload="check()" style ="display:none;">
<label class='listnames' id ='lblreason' style = 'width:150px; '></label>
<input type='text' name = 'status_reason' value = '<?=$status_reason?>' id ='reason' class='required-fields' style = ""/>
<label class='listnames' id ='date' style ='width:150px; '></label>
<input type='date' id ='lbldate' name='status_date' placeholder='mm/dd/yyyy' autocomplete='off' value ='<?=$status_date?>' style='height: 24px; ' class='required-fields'>
</div>
<select class="required-fields" id = "status" name="status" onload="check()" <?php if($prf_status == "Served") { echo "disabled"; } ?> >
<option value = "Outstanding" <?php if($prf_status == "Outstanding") { echo "selected = 'selected'"; } ?> >Outstanding</option>
<option value = "Served" disabled <?php if($prf_status == "Served") { echo "selected = 'selected'"; } ?> >Served</option>
<option value = "Cancelled" <?php if($prf_status == "Cancelled") { echo "selected = 'selected'"; } ?> >Cancelled</option>
<option value = "Hold" <?php if($prf_status == "Hold") { echo "selected = 'selected'"; } ?> >Hold</option>
</select>
You can't use onload on div.
You just need to "pull out" the code in the check function.
//function check()
//{
$(document).ready(function() {
if($('#status').val() == 'Cancelled' || $('#status').val() == 'Hold')
{
$('#prf').show();
$('#lblreason').show();
$('#lbldate').show();
$('#reason').show();
$('#date').show();
if($('#status').val() == 'Cancelled')
{
document.getElementById("lblreason").innerHTML = "Cancellation Reason";
document.getElementById("lbldate").innerHTML = "Date of Cancellation";
}
if($('#status').val() == 'Hold')
{
document.getElementById("lblreason").innerHTML = "Hold Reason";
document.getElementById("lbldate").innerHTML = "Date of Hold";
}
}
else
{
$('#prf').hide();
$('#lblreason').hide();
$('#lbldate').hide();
$('#reason').hide();
$('#date').hide();
}
});
//}
Try this example, using change event:
$(function() {
var prf = $('#prf'), lblreason = $('#lblreason'), lbldate = $('#lbldate');
var funcMap = {};
funcMap.Outstanding = function(){
prf.hide();
};
funcMap.Cancelled = funcMap.Hold = function(text) {
prf.show();
lblreason.text(text + ' Reason');
lbldate.text('Date of ' + text);
};
$('#status').on('change', function(e) {
var val = this.value;
funcMap[val](val);
}).trigger('change');//on page load
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="prf">
<label id='lblreason'></label>
<input type='text' id='reason' />
<label id='lbldate'></label>
<input type='date' id='date' placeholder='mm/dd/yyyy'>
</div>
<select id="status">
<option>Outstanding</option>
<option disabled=''>Served</option>
<option>Cancelled</option>
<option>Hold</option>
</select>

How to find Currently Selected value from this Custom HTML form Tag?

I have an element which is text box but its value is populated from another hidden select element.
<input type="text" id="autocompleteu_17605833" style="box-shadow: none; width: 119px;" class="mobileLookupInput ui-autocomplete-input" autocomplete="off" role="textbox" aria-autocomplete="list" aria-haspopup="true">
<select id="u_17605833" name="u_17605833" style="visibility: hidden">
<option value="127468">Virginia</option>
<option value="127469">Washington</option>
<option value="127470">West Virginia</option>
<option value="127471">Wisconsin</option>
<option value="127472">Wyoming</option>
</select>
var mySelObju_17605833 = document.getElementById("u_17605833");
$(function () {
var availableTagsu_17605833 = new Array();
for (var i = 0; i < mySelObju_17605833.options.length; i++) {
if (mySelObju_17605833.options[i].text != 'Other') {
availableTagsu_17605833[i] = mySelObju_17605833.options[i].text;
}
}
$("#autocompleteu_17605833").width($(mySelObju_17605833).width() + 5);
availableTagsu_17605833 = $.map(availableTagsu_17605833, function (v) {
return v === "" ? null : v;
});
$("#autocompleteu_17605833").autocomplete({
minLength: 0,
source: function (request, response) {
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i");
var a = $.grep(availableTagsu_17605833, function (item, index) {
var items = item.split(" ");
for (i = 0; i < items.length; i++) {
if (matcher.test(items[i])) return matcher.test(items[i]);
}
return matcher.test(item);
});
response(a);
},
close: function (event, ui) {
for (var i = 0, sL = mySelObju_17605833.length; i < sL; i++) {
if (mySelObju_17605833.options[i].text.toLowerCase() == $("#autocompleteu_17605833").val().toLowerCase()) {
mySelObju_17605833.selectedIndex = i;
$("#errorTDu_17605833").html("");
break;
}
mySelObju_17605833.selectedIndex = 0;
$("#errorTDu_17605833").html("Error: Invalid Input");
}
$("#autocompleteu_17605833").trigger("onchange")
}
});
});
$("#autocompleteArrowu_17605833").click(function () {
$("#autocompleteu_17605833").autocomplete("search");
$("#autocompleteu_17605833").focus();
});
$("#autocompleteu_17605833").focusout(function () {
for (var i = 0, sL = mySelObju_17605833.length; i < sL; i++) {
if (mySelObju_17605833.options[i].text.toLowerCase() == $("#autocompleteu_17605833").val().toLowerCase()) {
mySelObju_17605833.selectedIndex = i;
$("#errorTDu_17605833").html("");
break;
}
mySelObju_17605833.selectedIndex = 0;
$("#errorTDu_17605833").html("Error: Invalid Input");
}
$("#autocompleteu_17605833").trigger("onchange")
//$(this).autocomplete("close");
});
I want to find value selected in the hidden select box!
I tried to do the following
$("#autocompleteu_17605833").on("click", function (event) {
$((this.id).substring((this.id).indexOf("_") - 1)).attr("onchange", function (event) {
var selece = this.value;
alert(selece);
});
});
$("#autocompleteu_17605833").next().on("click", function (event) {
var selectedValue = document.getElementById((this.id).substring((this.id).indexOf("_") - 1)).value;
alert("Click on Arrow" + selectedValue);
});
$("#autocompleteu_17605833").on("change", function (event) {
var selectedValue = document.getElementById((this.id).substring((this.id).indexOf("_") - 1)).value;
alert("Changing the value" + selectedValue);
});
what I'm getting is older value where as I need the current assigned value.
How to achieve this??
WORKING DEMO
If am not wrong you want the selected value for this you can use select method
select:function(event,ui) {
alert("You have selected "+ui.item.label);
alert("You have selected "+ui.item.value);
}
This is a simple piece of code that will work as you required.
function result(){
document.getElementById("result").innerHTML= document.getElementById("u_17605833").value;
}
<html>
<head>
</head>
<body>
<div>
<select id="u_17605833" name="u_17605833" >
<option value="127468">Virginia</option>
<option value="127469">Washington</option>
<option value="127470">West Virginia</option>
<option value="127471">Wisconsin</option>
<option value="127472">Wyoming</option>
</select>
<input type="button" value="Show the result" onclick="result()"/>
</div>
<div id="result"></div>
</body>
</html>

Getting a label's value using select's name tag

I have a system that can output 0 or more select boxes and I need to add some Javascript/JQuery validation. I am new to writing JQuery and I am stuck getting the content of the text label for the error message: Here is an example of my select boxes form:
<div id="prodOptions" class="sale">
<p class="elevenText floatLeft">Product options</p>
<div class="floatLeft"><label for="colour">Select Colour</label>
<select name="colour">
<option value="" selected="selected">---</option>
<option value="blue">Blue</option>
</select>
</div>
<div class="floatLeft">
<label for="size">Select Size</label>
<select name="size">
<option value="" selected="selected">---</option>
<option value="small">Small</option>
</select>
</div>
<div class="floatLeft">
<label for="flavour">Select Flavour</label>
<select name="flavour">
<option value="" selected="selected">---</option>
<option value="cherry">Cherry</option>
</select>
</div>
and here is my javascript function which is called on form submission (the alerts are for testing):
function validateOptions()
{
selectList = $('select').get();
message = "";
for(i=0; i<selectList.length; ++i)
{
//alert(selectList[i].name);
selector = "for[=\""+selectList[i].name+"\"]";
alert(selector);
alert($(selector.value));
message += ($(selectList[i]).prop('selected', true).val() == "") ? "Please enter a value for \r\n" : "";
}
alert(message);
}
Your attribute syntax is incorrect. Your selector should be
var selector = "label[for='" + selectList[i].name + "']";
From there, you should fetch the label's .html(), rather than .val()
Also, labels should reference element ID's, rather than names. It is also not very clear how you want your message to be formatted. You should be able to do something like this:
function validateOptions()
{
var message = '';
$('select').each(function() {
if($(this).val() == '') {
var label = $('label[for="' + $(this).attr('id') + '"]');
message += 'Please select a value for: ' + label.html() + '\n';
}
});
alert(message);
}
You could also format your error message like so:
function validateOptions()
{
var emptyFields = [];
$('select').each(function() {
if($(this).val() == '') {
var label = $('label[for="' + $(this).attr('id') + '"]');
emptyFields.push(label.html());
}
});
if(emptyFields.length > 0) {
alert('Please select a value for:\n' + emptyFields.join('\n'));
}
}
function validateOptions() {
message = "";
$('select').each(function (i) {
message += ($(this).prop('selected', true).val() == "") ? "Please enter a value for" + $(this).prev().html() + " \r\n" : "";
});
alert(message);
}
$(document).ready(function(){ var allSelect = $('select');
$.each(allSelect,function(k,v){
var thIs = $(this);
var name = thIs.attr('name');
if(name == 'colour')
{
// Do what you want to do with colour select here eg:-
alert(thIs.prev('label').text());
} else if(name == 'size'){
alert(thIs.prev('label').text());
} else if(name == 'flavour'){
alert(thIs.prev('label').text());
}
return false;
});
});
$(document).ready(function(){
var allSelect = $('select');
$.each(allSelect,function(k,v){
var thIs = $(this);
var name = thIs.attr('name');
if(name == 'colour')
{
// Do what you want to do with colour select here eg:-
thIs.prepend('<option value="1">White</option>
<option value="2">Black</option>
<option value="3">Gray</option>');
} else if(name == 'size'){
// Do what you want to do with size select here
} else if(name == 'flavour'){
// Do what you want to do with flavour select here
}
return false;
});
});

Categories

Resources