To call Javascript Function from dynmaically created Textbox - javascript

In the below code i have a dynamically created textbox and on onfocus event i am calling a javascript function .And i am assign onfocus event values on page load .And it is not working after creating onfocus event.Pls help me to solve the issue.
Test1,Test2 values are assigned on pageload
function createFields(Test1,Test2) {
var newdiv = document.createElement('div');
if (type == "TextBox") {
newdiv.innerHTML +=
"<input class=\"form-control\" data-error=\"Please Provide "
+ DisplayName
+ "\" name=\""
+ Name
+ "\" value=\""
+ FieldValue
+ "\" onFocus=\""
+ HighlightField(Test1,Test2)
+ "\" id=\""
+ Name + "\"/>";
$('#divComplete').append(newdiv);
}
}
function HighlightField(Test1,Test2) {
}

on onfocus event i am calling a javascript function
No you're not. Look closely at what's happening here:
"onFocus=\"" + HighlightField(Test1,Test2) + "\"
You're calling HighlightField() immediately and setting its result to the onFocus handler.
Unless that function actually returns a string of valid JavaScript code, it's likely that your resulting HTML looks like this:
onFocus=""
If you want to call the function in the onFocus event, don't invoke it. Instead, just specify the function call in the string you're creating:
"onFocus=\"HighlightField(Test1,Test2)\""
Edit: Given the clarification on your question, it sounds like you want those variables to be interpreted right away. But not the function call itself. That would be done the same way it's done anywhere else in that string. Something like this:
"onFocus=\"HighlightField(" + Test1 + "," + Test2 + ")\""
Note that if those variables are expected to contain string data then you'd also need to add quotes (since strings need to be quoted):
"onFocus=\"HighlightField('" + Test1 + "','" + Test2 + "')\""
As you're probably starting to notice, dynamically building code like this is a bit unwieldy. Since you're using jQuery anyway, at the very least you should remove the in-line event handler and create a separate event handler elsewhere in the code. Something like:
$(document).on('focus', 'input.form-control', function () {
// handle your focus event here
});
Then you wouldn't need to build this complex string.

Related

Add onclick event for tr element dynamically from JavaScript

I am creating a table dynamically, I need to add an onclick event for each element as it is added, but this needs a dynamic parameter add, I have tried the following
trElements[i + 1].onclick = function () {
navigateToController('/Home/Client', "'" + machine.DeviceID + "'");
};
but this shows the onclick event as navigateToController('/Home/Client', "'" + machine.DeviceID + "'")
and not navigateToController('/Home/Client', 'DeviceName'); as I thought it would, I have also tried to have the onclick event in the html, and replace the DEVICEID with the actual deviceid.
var element = trElements[i + 1].outerHTML.replace('DEVICEID', machine.DeviceID);
trElements[i + 1].outerHTML = element;
this shows up as been correct, but when the page is loaded, it still has deviceid in there ?
I am sure it is something really simple... but any pointers would be appreciated.
I'm not entirely sure I understand the question, but it might be a scope issue. You might need to use bind to create the handler with the current value of DeviceID:
var machineId = 0;
function navigateToController(machineId) {
alert(machineId);
}
function addRow() {
var t = document.getElementById('thetable');
var tr = t.insertRow();
var td = tr.insertCell();
td.appendChild(document.createTextNode("machine " + machineId));
tr.addEventListener('click', navigateToController.bind(null, machineId));
machineId++;
}
<button onclick="addRow()">Add Row</button>
<table id="thetable"></table>
but this shows the onclick event as navigateToController('/Home/Client', "'" + machine.DeviceID + "'")
You're not going to see the value of the variable in the markup, if that's what you mean.
Why not just navigateToController('/Home/Client', machine.DeviceID )? It's already a string. No need to try to add quotes around it. You'd end up with a parameter that includes the quotes.
var deviceId = 'theDeviceId';
// This is not what you want. Notice this alert includes the single quotes as part of the string: "'theDeviceId'"
alert( "'" + deviceId + "'");
// This is what you want. This alert has just the (unquoted) value.
alert( deviceId );
The better way to do this is not to do it at all.
Better attach the event handler to existing container (the table in this case seems good) and check for bubbling events.
With jQuery is quite simple:
var myTable = $("table#theTable");
myTable.on("click", "tr", function(){ // Click event handler.
var clickedRow = $(this);
...
});
If you need some data related to each row, simply attach to it in "data-" attributes (i.e. «data-myId="someId"») of the tag. Then you could read them simply by clickedRow.data("myId") from event handler function.
This way you have single function to handle all events for all rows. Simpler and wasting too less mamory.
trElements[i + 1].onclick = (function () {
var deviceId = machine.DeviceID;
return function(){
navigateToController('/Home/Client', "'" + deviceId + "'");
}
})();
ok, so I couldn't get to the bottom of adding an onClick function dynamically, so, I changed my code around, and pass a viewModel array containing all the data I needed to create the table, so when I open the clients view, I send a list of all the relevant clients, and when I select the row I need, I just pass a single viewmodel of the client, I then update the html with the c# code #model.variable. I can easily update these from my signalr code once its created.
thanks for everyones input.
Just to update, I have found a solution I think, I could create the element, add the data to the innerHtml, and use:
setAttribute("onclick", "navigateToController('/Home/Client', '" + deviceId + "')");
I have used this in another part of my solution, and it works...

creating html paragraphs using javascript functions

I am writing a small game in javascript. When the user presses a button, text is returned. I am getting the feeling that there is an easier way than writing:
document.getElementById("logBox").innerHTML = "<p> X event is happening <p>" + document.getElementById('logBox').innerHTML;
So I am trying to write a function I can use like this:
function LOG(input){
document.getElementById("logBox").innerHTML = "<p> input <p>" + document.getElementById('logBox').innerHTML;
}
But even using the special characters sign like \ I have not been able to make it work. I have been searching for a solution but cannot seem to find one. Any suggestions? Thanks
function LOG(input){
// get the #logBox element, then keep it in a variable
// until the end of the function
var logBox = document.getElementById("logBox");
// This will never work -- unless you literally want to add a paragraph
// that says "input" each time you call this function.
// logBox.innerHTML = "<p> input </p>" ...
// Try this
logBox.innerHTML = "<p>" + input + "</p>" + logBox.innerHTML;
}

executing javascript inside href attribute of anchor tag

I checked a lot on Hrefs but couldn't get something related.
I am trying to do this in code behind which is actually a custom control class
writer.Write("<a href='javascript:document.location.href?" + filter.ParameterName + "=" + filter.QueryValue + "'>" + filter.UserVisibleValue + "</a>| ");
now this gets me something like this on hover of above anchor 'document.location.href?Test one=2013' and when i click it, this throws an obvious javascript error 'SyntaxError: missing : in conditional expression' because it takes it as a conditional operator and hence finds : missing.
I simply want that document.location.href (current url) should be calculated and the value put in where i use it.
I know that i may simply call a javascript function and inside that function i set the href but can i do it this way?
Try this:
writer.Write("<a href='javascript:window.location = document.location.href?" + filter.ParameterName + "=" + filter.QueryValue + "'>" + filter.UserVisibleValue + "</a>| ");
Note that you might have to escape values as needed otherwise JavaScript will become invalid. To prove that above approach works, you can copy-paste following simpler example in any HTML page and see it working:
bla

Why functionToCallOnOk I pass to my function does not get called when I attach it to callback via jQuery?

So I try such code:
function showAlertWithCallback(w, h, name, body_text, functionToCallOnOk) {
prepareWindow();
var ran_alert_number=Math.random()*50000;
$("#alert_content").html(body_text + '<br/>' + '<input type=\"button\" class=\"eButton\" value=\"Cancel\" onClick=$(\".alert\").hide() />' + '<input id=\"general-alert-'+ ran_alert_number +'\" type=\"button\" class=\"eButton\" value=\"OK\" onClick=\"$(\'.alert\').hide();\"/>');
$('#general-alert-' + ran_alert_number).click(functionToCallOnOk);
// also tried $('#general-alert-' + ran_alert_number).click(function(){functionToCallOnOk();});
showAlertBase(w, h, name);
}
called via something like:
showAlertWithCallback(
600,
100 ,
('New name for to ' + file_title + ' file.'),
'<input type="text" style="width:590px" class="text" value=\"' + file_title + '\">',
function(){
alert("hi!");
}
);
runs with no errors (chrome debugger) but function does not get called on OK click. Why and how to fix such thing?
Math.random()*50000 will produce a number like 38518.060150090605, which when you concatenate with '#general-alert-' in the jQuery call will produce a selector like this:
#general-alert-38518.060150090605
That will be treated as a selector which finds an element with id general-alert-38518 and class 060150090605, since the class name comes after the dot.
To make the random number, use, say, Math.floor(Math.random()*5000) instead.
A better option would be to use an incrementing global variable (eg, _global_counter++ each time you use it), then you would not have a chance of getting two elements with the same id.
An even better solution would be to create actual DOM elements in JavaScript, attach events to those elements, then insert those elements into the correct place in the document. That way they won't need to have ids at all.
Try removing the onClick attribute of the OK button.

Set name of a input box from a variable

I have this code
$("#inputs").append("<input class=\"adding\" id=\"test"+ values + "\ name=\"" + values + ">"+ values + "</input><br />");
I have a variable named values.
This code is put in the click method of it this appends the input box correctly but when I use AJAX to send the values and echo, it works fine only for the 1st value which I haven't used the jQuery append() function but instead just used HTML. What's my problem here?
Your question is generic without the relevant code snippets to your ajax, HTML and server code.
The only thing I can do is fix up your input creation code so that it's readable and maintainable.
$("#inputs")
.append(
$("<input />", {
"class": "adding",
"id": "test" + values,
"name": values,
"val": values
}))
.append($("<br/>"));
Simple rewrite with back slash:
$("#inputs").append("<input class=\"adding\" id=\"test" + values + "\" name=\"" + values + "\">"+ values + "</input><br />");

Categories