Script works in Chrome but not IE - javascript

It's so simple, but I don't know why IE isn't doing my innerHTML changes and other stuff.
function changeele2() {
document.getElementById("eleme2");
document.getElementById("workout");
document.getElementById("workoutweek");
if(workout.value == "Yes") {
eleme2.style.display = "inline-block";
workoutweek.className += " requiredField";
}
}
It called if I change the value of a Dropdown:
<select id="workout" onchange="changeele2()">
<option>No</option>
<option>Yes</option>
</select>
Neither works a Button with Text
I just can't find it out. Has anyone got an idea?

When you do document.getElementById("eleme2") you have to save the result of that operation and use that for subsequent access to that element.
function changeele2() {
var eleme2 = document.getElementById("eleme2");
var workout = document.getElementById("workout");
var workoutweek = document.getElementById("workoutweek");
if (workout.value == "Yes") {
eleme2.style.display = "inline-block";
workoutweek.className += " requiredField";
}
}
There are some browsers that make a global variable by the same name as the element id so that may be why it was sometimes working, but you should not rely on that.

This script shouldn't be working at all, chrome is salvaging it by looking up the elements by ID.
You should change it like this:
function changeele2()
{
var eleme2 = document.getElementById("eleme2");
var workout = document.getElementById("workout");
var workoutweek = document.getElementById("workoutweek");
if(workout.value == "Yes") {
eleme2.style.display = "inline-block";
workoutweek.className += " requiredField";
}
}

Related

Change liferay-ui:input-localized XML with javascript

I have the following tag in my view.jsp:
<liferay-ui:input-localized id="message" name="message" xml="" />
And I know that I can set a XML and have a default value on my input localized. My problem is that I want to change this attribute with javascript. I am listening for some changes and call the function "update()" to update my information:
function update(index) {
var localizedInput= document.getElementById('message');
localizedInput.value = 'myXMLString';
}
Changing the value is only updating the currently selected language input (with the whole XML String). The XML String is correct, but I am not sure on how to update the XML for the input with javascript.
Is this possible?
PS: I have posted this in the Liferay Dev forum to try and reach more people.
After a week of studying the case and some tests, I think that I found a workaround for this. Not sure if this is the correct approach, but it is working for me so I will post my current solution for future reference.
After inspecting the HTML, I noticed that the Liferay-UI:input-localized tag creates an input tag by default, and then one more input tag for each language, each time you select a new language. Knowing that I created some functions with Javascript to help me update the inputs created from my liferay-ui:input-localized. Here is the relevant code:
function updateAnnouncementInformation(index) {
var announcement = announcements[index];
// the announcement['message'] is a XML String
updateInputLocalized('message', announcement['message']);
}
function updateInputLocalized(input, message) {
var inputId = '<portlet:namespace/>' + input;
var xml = $.parseXML(message);
var inputCurrent = document.getElementById(inputId);
var selectedLanguage = getSelectedLanguage(inputId);
var inputPT = document.getElementById(inputId + '_pt_PT');
inputPT.value = $(xml).find("Title[language-id='pt_PT']").text();
var inputEN = document.getElementById(inputId + '_en_US');
if (inputEN !== null) inputEN.value = $(xml).find("Title[language-id='en_US']").text();
else waitForElement(inputId + '_en_US', inputCurrent, inputId, xml);
var inputLabel = getInputLabel(inputId);
if (selectedLanguage == 'pt-PT') inputLabel.innerHTML = '';
else inputLabel.innerHTML = inputPT.value;
if (selectedLanguage == 'pt-PT') inputCurrent.value = inputPT.value;
else if (inputEN !== null) inputCurrent.value = inputEN.value;
else waitForElement(inputId + '_en_US', inputCurrent, inputId, xml);
}
function getSelectedLanguage(inputId) {
var languageContainer = document.getElementById('<portlet:namespace/>' + inputId + 'Menu');
return languageContainer.getElementsByClassName('btn-section')[0].innerHTML;
}
function getInputLabel(inputId) {
var boundingBoxContainer = document.getElementById(inputId + 'BoundingBox').parentElement;
return boundingBoxContainer.getElementsByClassName('form-text')[0];
}
function waitForElement(elementId, inputCurrent, inputId, xml) {
window.setTimeout(function() {
var element = document.getElementById(elementId);
if (element) elementCreated(element, inputCurrent, inputId, xml);
else waitForElement(elementId, inputCurrent, inputId, xml);
}, 500);
}
function elementCreated(inputEN, inputCurrent, inputId, xml) {
inputEN.value = $(xml).find("Title[language-id='en_US']").text();
var selectedLanguage = getSelectedLanguage(inputId);
if (selectedLanguage == 'en-US') inputCurrent.value = inputEN.value;
}
With this I am able to update the liferay-ui:input-localized inputs according to a pre-built XML String. I hope that someone finds this useful and if you have anything to add, please let me know!
To change the text value of an element, you must change the value of the elements's text node.
Example -
xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue = "new content"
Suppose "books.xml" is loaded into xmlDoc
Get the first child node of the element
Change the node value to "new content"

Can i call another function inside the GetElement in Javascript

I am trying to call another function inside the getElement but it is not working everything when i change my selection. When i select Car, in the textbox my varxumb should populate. Any idea...
document.getElementById("mycall1").insertRow(-1).innerHTML = '<td><select id = "forcx" onchange="fillgap()"><option>Select</option><option>Force</option><option>Angle</option><option>Area</option></select></td>';
function fillgap() {
var xnumb = 20;
var forcxlist = document.getElementById("forcx");
if (forcxlist == "Force") {
document.getElementById("result1").value = xnumb;
}
}
I don't know how this "Force" value is coming to check.
you can try these solutions.
if (forcxlist == "Force")
instead use
var forcxlistText = forcxlist.options[forcxlist.selectedIndex].text;
if (forcxlistText == "Force")
or use value technique
<div id ="mycall1">
</div>
<div id ="result1">
</div>
<script>
document.getElementById("mycall1").innerHTML = '<td><select id = "forcx" onchange="fillgap(this.value)"><option value="1">Select</option><option value="2">Force</option><option value="3">Angle</option><option value="4">Area</option></select></td>';
function fillgap(value){
var xnumb = 20;
if (value == "2"){
document.getElementById("result1").innerHTML = xnumb;
}
}
</script>
or use
<div id ="mycall1">
</div>
<input type="text" id="result1" value=""/>
<script>
document.getElementById("mycall1").innerHTML = '<td><select id = "forcx"><option value="1">Select</option><option value="2">Force</option><option value="3">Angle</option><option value="4">Area</option></select></td>';
document.getElementById("forcx").onchange = function (){
var xnumb = 20;
var forcxlist = document.getElementById("forcx");
var forcxlistValue = forcxlist.options[forcxlist.selectedIndex].value;
if (forcxlistValue == "2"){
document.getElementById("result1").value = xnumb;
}
}
</script>
The forcxlist variable is an element object, returned by the document.getElementById method. Afterwards, you are checking if this element object is equal to "Force", which is a string (meaning the contents of your if block will never be executed). Did you mean to check if the contents of that object are equal to Force?
Instead of
if (forcxlist == "Force"){
use
if (forcxlist.innerHTML == "Force"){
I hope this helps!
Can't use innerHTML so i changed it to .value
document.getElementById("result1").value = xnumb;
There are a couple issues here.
First, you are expecting forcxlist to be a string, not an element, so you need to use .value to get the selected value of the dropdown.
Second, you should do your comparison with === not ==, as this ensures type equality as well, and is best practice.
I would also recommend building your select using HTML elements. It keeps things cleaner, is more readable, and is easier to maintain.
Since you are using the same id for the select, you would have to change the selector in your fillgap handler to var forcxlist = e.target.value;, this way the event will fire based on only the select that you are interacting with, regardless of how many rows you have in the table.
Updated code is below, and an updated working fiddle here. As per your comment about adding additional rows, the fiddle has this working as well.
<input type="button" value="Add Row" onclick="addDropDown()">
<table id="mycall1"></table>
<script>
function addDropDown() {
var tbl = document.getElementById("mycall1");
var newRow = tbl.insertRow(-1);
var newCell = newRow.insertCell(0);
newCell.appendChild(createDropDown("forcx", fillgap));
}
function createDropDown(id, onchange) {
var dd = document.createElement('select');
dd.id = id;
dd.onchange = onchange;
createOption("Select", dd);
createOption("Force", dd);
createOption("Angle", dd);
createOption("Area", dd);
return dd;
}
function createOption(text, dropdown) {
var opt = document.createElement("option");
opt.text = text;
dropdown.add(opt);
}
function fillgap() {
var xnumb = 20;
var forcxlist = e.target.value;
if (forcxlist === "Force") {
document.getElementById("result1").value = xnumb;
}
}
</script>
<input type="text" id="result1">

Value and Focus() not working on dynamically created inputs

I'm trying to create something to refresh the list of dates to all users every 30 seconds.
I dynamically create a table with the list of dates in my database using AJAX, the thing is that the refresh removes what the user was writing in the moment of the refresh so I'm saving what the user writes in javascript global variables, calling the refresh function, then filling the inputs with the information in the variables and focusing the input the user was on.
The thing is the inputs aren't filled nor focused.
this is my relevant code here:
var identificacionc = "";
var nombresc = "";
var apellidosc = "";
var telefonoc = "";
var posicionc = 0;
var ladoc = 0;
//This is called on input onfocus to record the id
function recuerdo(posicion, lado)
{
posicionc = posicion;
ladoc = lado;
}
function actualizar()
{
//This line is not relevant
listaragenda();
if (document.getElementById("datepicker").value != "")
{
//put the info in the global variables and it works even if they're dynamically created
identificacionc = document.getElementById("txtidentificacion" + posicionc).value;
nombresc = document.getElementById("txtnombres" + posicionc).value;
apellidosc = document.getElementById("txtapellidos" + posicionc).value;
telefonoc = document.getElementById("txttelefono" + posicionc).value;
//Here is where I call the function to refresh dates
listarcitas();
}
}
function listarcitas()
{
var objAjax = crearObjeto();
var fecha = document.getElementById("datepicker").value;
objAjax.open("POST", "clases/listarcitas.php", true);
objAjax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
objAjax.onreadystatechange = function()
{
if (objAjax.readyState == 4 && objAjax.status == 200)
{
document.getElementById("citaslistadas").innerHTML = objAjax.responseText;
//Checks if any global variable is not empty to start to fill them with the info
//nothing inside this If works
//posicionc and ladoc have the correct values
if (identificacionc != "")
{
document.getElementById("txtidentificacion" + posicionc).value = identificacionc;
document.getElementById("txtnombres" + posicionc).value = nombresc;
document.getElementById("txtapellidos" + posicionc).value = apellidosc;
document.getElementById("txttelefono" + posicionc).value = telefonoc;
if (ladoc == 1)
{
document.getElementById("txtidentificacion" + posicionc).focus();
}
else if (ladoc == 2)
{
document.getElementById("txtnombres" + posicionc).focus();
}
else if (ladoc == 3)
{
document.getElementById("txtapellidos" + posicionc).focus();
}
else if (ladoc == 4)
{
document.getElementById("txttelefono" + posicionc).focus();
}
}
}
}
objAjax.send("fecha=" + fecha);
}
//the interval every 30s
window.setInterval("actualizar()", 30000);
Everything retrieved from AJAX works fine everything is listed, even in the web browser console I make alerts of the variables, set the values and focus the dynamically created inputs, everything works fine.
But why this is not working in the code?
Thanks in advance

Javascript find missing select value

I have the following JavaScript:
var next_user = "1";
i=0;
for (i=0;i<=10;i++)
{
var el = document.getElementById("user_list");
var val = el[i].value;
if (val <= next_user)
{
next_user = i;
}
if (val >= next_user)
{
next_user = i;
}
alert(next_user);
}
and I have following Select box on the screen:
<select id="user_list" onclick="load_user(this)" name="user_list" size="21" style="width:200px;">
<option value="1">Bob</option>
<option value="2">john</option>
<option value="3">Frank</option>
<option value="5">tom</option>
</select>
I can't seem to get it working the way I want it to.
The select box could have 10 users in the list and each of the (options) values are unique (1-10).
as you can see in my select box I am missing value 4. My Javascript code from above is meant to go though the select box and find the first value that is missing. (in my above example, it should reply back with 4 as that is missing) but If Bob is missing then it should reply back with 1.
Well that's what my JavaScript code above should be doing but I can't seem to work out what I am doing wrong. (well I hope I am doing it correct)
does anyone know what I am doing wrong?
(I am not plaining to use any jQuery at this stage)
You should use options property of that select element you extracted.
Example:
<script>
var userList = document.getElementById("user_list");
for (var i=0;i<userList.options.length; i++) {
if (userList.options[i].value != (i+1)) {
alert((i+1)+" is missing");
break;
}
}
</script>
You can use the following code to alert the missing Option
var next_user = 1;
var el = document.getElementById("user_list");
for (i = 0; i < 10; i++) {
var val = parseInt(el[i].value);
if (val > next_user) {
alert(next_user);
break;
} else {
next_user++;
}
}​
Demo: http://jsfiddle.net/joycse06/75kM7/

Javascript - How to enable/disable text input in IE9

The following script worked in IE8 but not in IE9:
function toggleSelect(fieldName)
{
var idx = fieldName.lastIndexOf("_");
var sub = fieldName.substring(19,idx);
if (document.findForm["cb_Row_PageAutoDelete_" + sub].checked) {
document.findForm["SHIP_QTY_" + sub].disabled=false ;
} else {
document.findForm["SHIP_QTY_" + sub].disabled=true ;
}
return true;
}
I can display the value of the SHIP_QTY field so I know it's on the page but the disable function does not work.
Thanks for your help.
If findForm is the name of the form, you want window.findForm rather than document.findForm. You can also just use the result of the other field's checked property directly rather than an if/else. So your code changes to:
function toggleSelect(fieldName)
{
var idx = fieldName.lastIndexOf("_");
var sub = fieldName.substring(19,idx);
window.findForm["SHIP_QTY_" + sub].disabled = window.findForm["cb_Row_PageAutoDelete_" + sub].checked;
return true;
}

Categories

Resources