javascript onchange event calling a function with multiple arguments - javascript

I am having problems with the following code:
I have n numbers of select box, whose id are differentiated by the values that the variables ModName and level take:
container.innerHTML = '<form id="listToolForm_'+ModName+level+'"><select id="listToolSelect_'+ModName+level+'" onChange="selValue(this.selectedIndex,'+ModName'+, level)"><option value="0">---</option></select></form>';
The select box is then populated by values taken from a database (this part is not really relevant here). With each form, there is a hidden input with id= idArg'+ModName+'_lev'+level, that will store the index selected by the user, using onChange and the function selValue(x):
Here is the function selValue(index, ModName, level):
function selValue(index, ModName, level){
document.getElementById("idArg"+ModName+"_lev"+level).value = index;
}
I tried the script setting var ModName = "SL", and var level = 0. I get an error: 'SL is not defined'. Another test that worked is by replacing the function that fires up onChange:
onChange="selValue(this.selectedIndex)"
and
function selValue(index){
var level = 0;
var ModName = "SL";
document.getElementById("idArg"+ModName+"_lev"+level).value = index;
}
So if the function fired up onChange has one argument, the code works, but does not when using several arguments. I suspect it's because of the line:
onChange = "selValue(this.selectedIndex,'+ModName'+, level)"
I tried:
onChange="'+window["selValue"](this.selectedIndex, ModName, level)+'"
without success.

The following (I assumed '+ModName'+ was a typo in the question and not in the actual code):
onChange="selValue(this.selectedIndex, ' + ModName + ', level)"
causes JavaScript to substitute ModName with its value, which results in the actual HTML being:
onChange="selValue(this.selectedIndex, SL, level)"
When handling the onChange event, the JavaScript engine "thinks" SL is a variable (hence the error), but you actually want it to be a string (if I understood well).
To turn SL into a string, you should surround it with single quotes. To do that, you will need the \' escape sequence, since you're already using nested quotes. Simply replace:
onChange="selValue(this.selectedIndex, ' + ModName + ', level)"
with:
onChange="selValue(this.selectedIndex, \'' + ModName + '\', level)"
Also, didn't you mean:
onChange="selValue(this.selectedIndex, \'' + ModName + '\', ' + level + ')"
?

Related

How to change only the second parameter of an onclick function when it's clicked

I have an onclick handler with two parameters. When it's clicked I want to update only the second parameter value. I prefer jQuery.
I have tried all kinds of jQuery combinations.
The included code works but I want to exclude replacing the first parameter.
The link:
<a href="#" id="messageremove" onclick="messageremove('param1', 'param2')"
The jQuery code:
$("#messageremove").attr('onclick', 'messageremove(' + "'" + param1 + "'" + ', ' + "'" + param2_new + "'" + ')');
I want to exclude replacing the first parameter, but right now both are being replaced.
Pass the variables, store the before variable and the new variable. Then update accordingly. I just switched them in this exmaple.
let before = '';
let after = '';
function messageremove(param1, param2) {
before = param1;
after = param2;
$("#messageremove").attr('onclick', `messageremove(`+ after + `,` + before + `)`)
console.log($("#messageremove").attr('onclick'))
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Switch

loading saving and showing json results in javascript

I have a php file called rows2.php that shows results like so after entering new fields in a database. It is simply showing the new id of the field :-
{'new_id':'92'}
I want to load this with javascript and add the new_id to existing list with : either side of the number and display it but I seem to be struggling? Many thanks.
The javascript to load the page and get the result is :
$.getJSON("rows2.php", function(result) {
var new_id=console.log(result[0].new_id);
document.getElementById('vehicle_list').value = '' + document.getElementById('vehicle_list').value + 'new_id' + ':';
})
You should use
document.getElementById('vehicle_list').innerHTML = ''+document.getElementById('vehicle_list').innerHTML+'new_id'+':';
instead of
document.getElementById('vehicle_list').value = ''+document.getElementById('vehicle_list').value+'new_id'+':';
.value is used only in case of input elements otherwise you must use .innerHTML
Don't put the variable name (new_id) in quotes.
document.getElementById('vehicle_list').value = '' + document.getElementById('vehicle_list').value + new_id + ':';

eval javascript function IE6 taking long time

I have the below chunk of code. I've debugged through and located the snippet that is causing a long delay in IE6.
Basically the code loops through a document converting it to XML and sending to a PDF. On Ubuntu and Firefox 4 it takes 3 seconds. On IE it can take up to 40 seconds regularly.
/**
* This function builds up the XML to be saved to the DM.
*/
function getXMLToSave(){
var text="<workbook><sheet><name>Adv4New</name>";
//show_props(document.adv4.row10col1, "document.adv4.row10col1");
for(i=1;i<157;i++){
text = text + "<row number='" + i + "'>";
for(j=1;j<=7;j++){
text = text + "<col ";
//alert(eval('document.adv4.row'+i+'col'+j+'.readonly'));
try{
text = text + "number='" + j + "' label='" + eval('document.adv4.row'+i+'col'+j+'.className')+ "'";
}
catch (e) {
text = text + "number='" + j + "' label=''";
}
try {
if(eval('document.adv4.row'+i+'col'+j).readOnly)
text = text + " type='readonly'";
else
text = text + " type=''";
}
catch (e) {
text = text + " type=''";
}
try {
text = text + " color='" + eval('document.adv4.row'+i+'col'+j+'.style.color') + "'";
}
catch (e) {
text = text + " color=''";
}
text = text + ">";
try {
// don't wrap in a CDATA (like previously), but run cleanNode
// this fixes html entities
var content = eval('document.adv4.row'+i+'col'+j+'.value');
text = text + cleanNode(content);
}
catch (e) {
text = text + "0";
}
text = text + "</col>";
}
text = text + "</row>";
}
text = text + "</sheet></workbook>";
return text;
}
I believe its the eval function causing the delay in IE6. Is there a neat solution to fix this. Thanks very much
Why are you using eval in the firts place?
eval('document.adv4.row'+i+'col'+j+'.style.color')
Use bracket notation!
document.adv4["row"+i+"col"+j].style.color
You don't need eval() at all:
text = text + "number='" + j + "' label='" + document.adv4['row' + i + 'col' + j].className + "'";
Also, in IE6 (but not in newer browsers), building up large strings by repeatedly adding more content is really, really slow. It was way faster in that browser to build up strings by creating an array of substrings and then joining them all together when finished with all the pieces.
Don't use eval EVAL is EVIL. Having said that, you really shouldn't care about IE6: Even MS doesn't support it any longer, why should you bother?
Anyhow, change all eval calls like:
eval('document.adv4.row'+i+'col'+j+'.value');
to
document.adv4['row' + i + 'col' + j].value;
To access the elements directly. Remember that Nodes are objects, so their properties can be accessed either using the dot-notation (foo.bar) or the "associative array" notation: foo['bar'], the latter being very useful when you need the value of a variable to access properties
Don't use eval - period. The eval() should be renamed to evil(). There is almost no situation where you really need to use the eval function.
In this case you can use document.getElementById() to find a DOM node with a specific id.
It's likely that it's all the string concatentation that makes it slow. Each time you add something to the text, it will copy all the previous text into a new string.
Newer browsers have optimised code for this special case, so for them the impact is less.
Instead of concatenating strings like this:
text = text + "something";
use an array instead:
var text = [];
then add items to the array using the push method:
text.push("<workbook><sheet><name>Adv4New</name>");
Finally just join the strings together:
return text.join('');
One solution could be generating a color array (or maybe an object if you need it) and then using it.
But then, ask yourself the question "Should I really support IE6?"

Calling Html Helper Method from Javascript Function

I am trying to call a custom Html helper method that I have written from a javascript function that is used by jqGrid to return formatted text, in this case a link, for a cell:
function formatGroupPlanEditLink(cellValue, options, rowObject) {
//var cellHtml = "<a href='/Insurance/GroupPlanEdit/?id=" + rowObject[0] + "'>" + rowObject[1] + "</a>";
var functionArgs = rowObject[1] + ',Url.Action("GroupPlan", "Insurance", new { id = ' + rowObject[0] + ' }),String.Format("Edit {0}", ' + rowObject[1] + '), listId,Url.Action("GroupPlanList", "Insurance"),false';
var cellHtml = '#Html.DialogFormLink(' + functionArgs + ')';
return cellHtml;
}
The problem that I have is that I cannot concatenate the entire string before the helper is executed. So the browser is trying to execute "#Html.DialogFormLink(" - which of course causes an error. I guess there must be a better way to go about this. I really want to still be able to use the Html helper method as I use it elsewhere, and it works nicely for my requirements.
I'm not that familiar with Razor, but the quotes around the #Html helper look suspicious.
var cellHtml = '#Html.DialogFormLink(' + functionArgs + ')';
The browser doesn't execute #Html.DialogFormLink; the server evaluates it. I suspect the server is injecting the literal '#Html.DialogFormLink' into your js.

jQuery - parsing JSON data - Having trouble with variable name

My first delve into working with JSON data. I have a bit of experience using jQuery though.
I'm posting to this URL (tumblr api): jyoseph.com/api/read/json
What I'm trying to do is output the json that gets returned. What I have so far:
$(document).ready(function(){
$.getJSON("http://jyoseph.com/api/read/json?callback=?",
function(data) {
//console.log(data);
console.log(data.posts);
$.each(data.posts, function(i,posts){
var id = this.id;
var type = this.type;
var date = this.date;
var url = this.url;
var photo500 = this.photo-url-500;
$('ul').append('<li> ' +id+ ' - ' +type+ ' - ' +date+ ' - ' +url+ ' - ' +photo500+ ' - ' + ' </li>');
});
});
});
See my jsbin post for the entire script: http://jsbin.com/utaju/edit
Some of the keys from tumblr have "-" hyphens in them, and that seem to be causing a problem. As you can see "photo-url-500" or another "photo-caption" is causing the script to break, it's outputting NaN.
Is there a problem with having hyphens in the key names? Or am I going about this all wrong?
If there are dashes in the names you'll need to access them differently. Change var photo500 = this.photo-url-500; to read var photo500 = this["photo-url-500"];.
Please note it is best not to append inside each iteration. Better to append to a string or push to an array then append once after the iterator has finished. Appending to the dom is expensive.
Use the bracket notation to access the members:
var photo500 = this['photo-url-500'];

Categories

Resources