Javascript Generating Text into Textbox? - javascript

I wrote this little bit of code but I'm not sure why it's not working? It's supposed to take in the persons name and depending on what they selected it will output a website with their name at the end of it.
JSFiddle
http://jsfiddle.net/tQyvp/135/
JavaScript
function generateDynamicSignature() {
var dynSig = "";
var user = document.getElementById("usernameInput");
var e = document.getElementById("scriptListInput");
var strUser = e.options[e.selectedIndex].text;
if (strUser == "example") {
dynSig = "http://example.com/users/";
}
document.getElementById("generateSignature").addEventListener('click', function () {
var text = document.getElementById('dynamicSignatureOutput');
text.text = (dynSig + user);
});
}
HTML
<select class="form-control" id="scriptListInput">
<option value="example">Example 1</option>
</select>

There are a few problems with your code, I'll try to list them all.
First, you never added the username input to your HTML.
Next, you seem mixed up on the way to access/set the text of an HTML input. You do this through the value field. For the username input, you forgot to access any property, so you'll need to change it to:
var user = document.getElementById("usernameInput").value;
You later used the text property of both the select element and the output. These should also both be value.
Another problem is that you've placed a listener inside a listener. Your outer function, generateDynamicSignature, listens for the onclick event of the button. This function only runs after the button is clicked. But inside this function, you attach a new listener. This inner listener will only run if someone clicks the button twice.
I've included these changes in a new fiddle:
https://jsfiddle.net/zdfnk77u/

where is usernameInput in your html?
in the if, use === instead of ==

If and when you add the missing "usernameInput" element in your HTML, all you'll have to do is...
dynSig='http://example.com/users/'+usernameInput.value;

I think part of the problem is that you want to access the value and not the text of input elements. So for text and strUser, you want to do text.value instead of text.text and such.
Also, based on the JSfiddle, you probably want to rewrite how you're using the document listener and the onclick of the html element. Every time the button is clicked it goes through the generateDynamicSignature and creates a listener to change the value, but doesn't necessarily change the value itself. If you move the logic of the generate function inside the click listener, that should fix most of your problems.

You create your generateDynamicSignature inside $(document).ready.
There are two approaches.
define function generateDynamicSignature outside
$(document).ready
or
bind your button.click to a handler inside $(document).ready
Do not mix these two.

Related

Add JavaScript onClick to dynamically generated asp button

Background My page creates a list of objects based on rows of an SQL Database. For each object, a DIV is dynamically generated that contains a few items including a LinkButton and a further child DIV that is initially hidden. I want the link button to toggle the child DIV's hidden property. The JavaScript is not dynamically generated and is included in the ASPX page.
Problem I don't know how to make this generated LinkButton fire JavaScript that is included in the ASPX page and pass in the correct DIV's ID.
I'm guessing I need to add an attribute to the button like so:
myButton.Attributes.Add(reference to JS function + parameter of DIV's ID)
Maybe like:
myButton.Attributes.Add("onclick", "Show_Hide_Display('"<%="' +idString+ '".ClientID%>"')");
Where the button is given an attribute of a JS onClick handler pointing to the function "Show_Hide_Display" and a parameter of a DIV's ID that is calculated as the rendered ID. This syntax is incorrect though.
How do I write this so it calls 'Show_Hide_Display' and passes the ID of the current child DIV? All of the DIVs have the same ID apart from a number that references their row number, for example '"myDiv_" + counter.ToString'
The JavaScript I am trying to add a call to on the button:
function Show_Hide_Display(divID) {
var div = document.getElementById(divID);
var style = document.defaultView.getComputedStyle(div);
var display = style.getPropertyValue('display');
if (display == '' || display == 'block') {
div.style.display = 'none';
} else {
div.style.display = 'block';
}
}
Use the following syntax ...
myButton.Attributes.Add("onclick", "Show_Hide_Display(this.id);");
the above syntax allows to call the function with id as its parameter.
suggestion:
Try to write a common function which does not depend on generated ids of controls.
If this is not useful for your requirement, please post your code which might gives me a better idea.
If you are using jQuery, you could you jQuery delegate method.
$(document).on("click", "div.parent", function(){
var subDivId = getSubDivByParent(this);
Show_Hide_Display(subDivId);
};
You need to implement getSubDivByParent according your DOM structure.
If you are not using jQuery, you need to attach event yourself. For each dynamically generated element. You need to manually add following script in your server code to register event.
... your html code ...
<script>
var elem = document.getElementById('new-created-element');
elem.addEventListener("click", function(){
var subDivId = getSubDivByParent(this);
Show_Hide_Display(subDivId);
};)
</script>
My suggestion is use jquery to achieve the functionality.
My solution works if you want to toggle the immediate div for the link.just call onclientclick method to toggle the div.
in linkbutton onclientclick="Show_Hide_Display(this)"
function Show_Hide_Display(id) {
$(id).next('div').toggle();
}
I hope this helps you .. Thanks

JQuery catch an event on Paragraph change

I would like to make a script that, when the text of a certain paragraph change, start a certain function, I tried the follow but i don't think the method change() works for a paragraph
$("#myParagraph").change(function(){......})
You would wrap that tag or "paragraph" in a container, and bind that container to a event possibly. You could also look into using the length of the "text" property. During this triggered event, check that the state is different. I can write an example if you need one. One place to look at is the
//global variable. Store in hidden field if you would like.
var currentVal = $('element').text();
$('element').bind("DOMSubtreeModified",function(){
var newVal = $(element).text();
if(currentVal != newVal)
{
//call function here.
}
});
This is basic and very simple, but to give you the idea.

Why are only some attributes updated from my javascript function?

I have a button script to change the buttons in a frame based on the page loaded in the main frame. The problem I'm experiencing is that while the background images, tabindex and text on the button (innerHTML) all change as expected, the onclick doesn't. It appears to completely ignore it. Here's the script I'm using:
function createbutton(btn_N, btn_I, btn_L, btn_D) // (Div Name, Tab Index, Button Text, Page To Load){
var btnN = top.frames['buttonbar'].document.getElementById(btn_N);
btnN.style.cssText = "display:block; cursor:pointer; padding-left:16px; padding-top:5px;";
btnN.onmouseover = function() {this.style.backgroundImage = "url('./osdimages/navBG_roll.png')";};
btnN.onmouseout = function() {this.style.backgroundImage = '';};
btnN.tabindex = btn_I;
btnN.innerHTML = btn_L;
btnN.onclick = btn_D;
}
The button call looks like this:
createbutton("button01", 1, "New Order/Browse", "parent.frames['content'].location.href='createorder/createorder.asp';");
There is a difference between attributes and properties.
The best example of this is as follows:
HTML: <input type="text" value="hello" id="test" />
Type something in the text box
document.getElementById('test').value is whatever you typed
document.getElementById('test').getAttribute("value") is whatever was in the HTML
Some attributes are directly mapped to properties and vice versa, but this is not always the case.
For instance, the onClick attribute takes a string that is then eval'd, but the onclick property takes a function. This is why your code isn't working.
Either pass a valid function, or use setAttribute.
You are setting onclick with a string, it needs a function to execute.
createbutton("button01", 1, "New Order/Browse", function(){ parent.frames['content'].location.href='createorder/createorder.asp'; });

How do read/write <input> values in an HTML document with JavaScript?

I have an <input> in my document. There I want the user to do some input.
var myVar = document.getElementById('userInput').value;
Then I want this value to be shown in another <input>.
document.getElementById('Preview').value = myVar;
This code somehow doesn't work.
Can anybody help?
Thanks in advance!
Update based on further information in comments before:
<button onClick="calculateThatObscenityDeleted()">"Save"</button >
Submit buttons will submit forms, thus running the JS but immediately blanking the form.
(That might still not be the actual issue, the question is still missing most of the code)
Original answer before it was revealed that the question didn't reflect the problem:
var myVar=document.getElementById('userInput').value;
Don't forget the =.
(And, obviously, you need to use that code in an event handler so it isn't executed only when the document loads and before the user has typed anything.)
Is it form?
Try something like this:
oFormObject = document.forms['myform_id'];
oFormObject.elements["element_name"].value = 'Some Value';
Besides the typo, you have to bind an event handler to the first <input>:
var input_a = document.getElementById('userInput');
var input_b = document.getElementById('Preview');
input_a.onkeyup = function(){
input_b.value = input_a.value;
}

Failed to set event handler in javascript

I want to add an event handler for input text controls. The controls is generated dynamically. My code is like:
JavaScript:
var settings_check = new Array("checkVMName()","checkDiskMB()","checkMemMB()","checkEsx()","checkDatastore()");
...
_inputbox = document.createElement("input");
_inputbox.type = "text";
_inputbox.id = settings[zindex];
_inputbox.onblur = settings_check[zindex];
_hint = document.createElement("hint");
_hint.id = settings[zindex] + "_Label2";
_hint.innerText = settings_hint[zindex];
mycurrent_cel2.appendChild(_inputbox);
mycurrent_cel2.appendChild(_hint);
But this way doesn't work. I checked the HTML with Firebug, and no "onblur" attribute for the input text control at all.
HTML
<tr>
<td>....</td>
<td><input type="text" id="Datastore">
<hint id="Datastore_Label2">start with /</hint>
</td>
</tr>
I also tried other ways to set event handler like
_inputbox.onblur = function(){alert("test");};
or
_inputbox.setAttribute("onblur",func);
Neither works. :(
If I manually add onblur=function(){...} for the input text control in the HTML with Firebug and execute, the onblur does work. So the question is: how can I set event handler for a control in JavaScript? Is there anything wrong in my code? Thanks.
You are creating an array of strings with function invocations in them, this is completely incorrect.
You need to assign references to the functions that you wish to be invoked when the event fires. You'd do this by simply storing the names of the functions (without the () or quotes) in your array, and it should work (the functions must be previously defined in the current scope as well):
var settings_check = [checkVMName, checkDiskMB, checkMemMB, checkEsx, checkDatastore];
So, in essence, settings_check is simply an array of function references.
See this jsFiddle example illustrating this concept.

Categories