Want to call a javascript function with 2 parameters in innerhtml - javascript

I have a JSP containing JavaScript function.Within that I created an inner html code.That contain a button with onClick function.When clicking the button I want to pass 2 parameters to the the function of JavaScript. But I can't get the 2 values properly.Please help me
Thank you
<script type="text/javascript">
function find(){
var i=0;
var servicetypevalue="SERVICE";
var td7= document.createElement("td");
td7.innerHTML='<input type="button" value="View Status" class=button name="ptBtn" id="ptBtn" onClick="getStatus('i,servicetypevalue');">';
}
function getStatus(i,servicetypevalue){
alert("enter");
}
</script>
I want to show the enter alert.But the parameter values are not properly passed.

td7.innerHTML='<input type="button" value="View Status" class=button name="ptBtn" id="ptBtn" onClick="getStatus(' + i + ',' + servicetypevalue + ');">';
use string concatenation as given above.

If your'e going to generate your own elements in JS, it's different than jQuery. While in jQuery you can make strings into valid markup reliably, but JS is not as sophisticated. Yes you can make an element by innerHTML, but it's error prone. The procedure to accomplish what you want in plain JS is as follows:
#1. Create an element.
#2. Append element to a parent.
#3. Add attributes to element.
The way your code is, it wouldn't work because your'e skipping #2. .td7 is never appended on the DOM and if the innerHTML of .td7 was rendered, it might succeed that'd be wierd. Instead of using an inline event which limits you, addEventListener gives you much better control and is more manageable. Also your getStatus just alerts "enter" which doesn't prove that your 2 parameters actually were passed. I added another alert as proof that the parameters were passed.
var i = 0;
var servicetypevalue = "SERVICE";
var host = document.querySelector('body');
var td7 = document.createElement('td'); //#1
var ptBtn = document.createElement("button"); //#1
host.appendChild(td7); //#2
td7.appendChild(ptBtn); //#2
ptBtn.className = "button"; //#3
ptBtn.name = "ptBtn"; //#3
ptBtn.id = "ptBtn"; //#3
ptBtn.innerHTML = "View Status"; //#3
function getStatus(i, servicetypevalue) {
alert("enter");
alert("i: " + i + "\nservicetypevalue: " + servicetypevalue)
}
ptBtn.addEventListener('click', function(event) {
getStatus(i, servicetypevalue);
}, false);
window.load = find;
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
</body>
</html>

Try to replace
td7.innerHTML='<input type="button" value="View Status" class=button name="ptBtn" id="ptBtn" onClick="getStatus('i,servicetypevalue');">';
to
td7.innerHTML='<input type="button" value="View Status" class=button name="ptBtn" id="ptBtn" onClick="' + "getStatus('i','servicetypevalue'" + ');">';

Related

How can I reuse result from JQuery for javascript textual matching?

I have html elements coming into function as string, then I am injecting elements into it as string however to my surprise it didn't work.
something like:
var replacement = $(row).find('td:last').append("<script type=\"text/javascript\"> function remove" + override.SessionKey + "(){ $('tr[session-key=\"" + override.SessionKey + "\"]').remove(); }</script><input type=\"button\" value = \"Remove\" onClick=\"remove" + override.SessionKey + "()\" />")
row.replace($(row).find('td:last')[0],replacement[0])
After some further investigation I have narrowed it down to matching failing in replace function, basically after you search with JQuery result cannot be used for textual matching
Here is an example of what I mean:
var r = "<tr class=\"hide\" session-key=\"SessionProductDataMotorEnrichmentSagaFactorScore\" session-key-data-type=\"Decimal\"><td id=\"tdDisplayName91\">SagaFactorScore</td><td id=\"tdValue91\"></td></tr>"
$('div').text(r.indexOf($(r).find('td:last')[0]));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div></div>
One would expect to always have a match as I am using contents of original html string.
How can I reuse result from JQuery for textual matching?
I think you're looking for .outerHTML:
var r = "<tr class=\"hide\" session-key=\"SessionProductDataMotorEnrichmentSagaFactorScore\" session-key-data-type=\"Decimal\"><td id=\"tdDisplayName91\">SagaFactorScore</td><td id=\"tdValue91\"></td></tr>"
$('div').text(r.indexOf($(r).find('td:last')[0].outerHTML));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div></div>
That is a terrible way of doing what you're trying to do.
var btn = $("<button></button>");
btn.attr("type","button").text("Remove").on("click",function() {
var tr = $(this).closest("tr");
tr.remove();
});
This creates the button with associated event bound directly to it. You can then append it to all rows, for instance, like so:
$("tr>td:last-child").append(function() {return btn.clone(true);});

Get the value of an <input type="text"> that was created dynamically inside a modal

i would like to get the value of an <input type="text"> that was created dynamically inside a modal and put it into variable "newcomment".
This is how i make the input:
var newcomment;
var p = $("<p>");
p.append("Some text");
p.append("</p>");
p.append("<input type='text'id='comment_text' value='Comment'"+"onblur=newcomment=$('#comment_text').val()"+" onfocus=if(this.value==this.defaultValue)this.value=''>"+"</input>");
$("div.modal-body").append(p);
The problem is when i write something like "ok" inside the textbox in the modal, and after i focusout from the textbox: newcomment seems not update to "ok" and still have the default "Comment" value.
1st: You need to use newcomment=this.value instead of newcomment=$('#comment_text').val()
2nd: No need to add + signs in your input html code while you not trying to concatenate string by putting variables to it
var newcomment;
var p = $("<p>");
p.append("Some text");
p.append("</p>");
p.append("<input type='text' id='comment_text' value='Comment' onblur='newcomment=this.value; alert(newcomment);' onfocus=if(this.value==this.defaultValue)this.value='' />");
$("body").append(p);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Not really the answer here, but might help you get at the root of the problem.
JS:
var newComment, defaultValue;
function doOnBlur(){
newComment = $('#comment_text').val()
}
function doOnFocus(){
if($('#comment_text').val() == defaultValue){
$('#comment_text').val('')
}
}
HTML:
<input type='text' id='comment_text' placeholder='Comment' onblur='doOnBlur()' onfocus='doOnFocus()' />
<!-- inputs dont have a close tag, also should use placeholder for temporary text -->
from here, you can set breakpoints in the debugger and see where your code is going wrong. You can also modify the functions much more easily rather than writing the executing code in the HTML

Taking a HTML form <input> value and using it to modify a <p> tag with Javascript

I am fairly new to Javascript and am trying to create a simple madlib application where a user can input a word through an HTML page and have that word appear in a paragraph tag when the user clicks the "submit" button. I am having troubles displaying the word that the user inputs. I know that I am close but for the life of me cannot figure out what I am missing.
Here is the HTML I am using:
<form>
<label>Word</label><input id="word"></input>
<input type="submit" value="submit" id="submitButton"></input>
</form>
<p id="story"> A {userWord goes here} is now part of the story </p>
And the Javascript:
var word = document.getElementById('word').innerHTML,
originalStory = document.getElementById('story'),
button = document.getElementById("submitButton");
button.onclick = function(){
replaceStory(word);
};
var replaceStory = function(userWord) {
var story = ("A " + userWord + " is now part of the story");
return originalStory.innerHTML = story;
};
Here is a JSFiddle: https://jsfiddle.net/5c4j2opc/
I have made a new JSFiddle: https://jsfiddle.net/5c4j2opc/3/ which works.
I changed type="submit" to type="button" to stop the page refreshing when the button is clicked and moved the word variable to the replaceStory function so it doesn't just get called once at the beginning of the script! Hope this helps.
You have to change two things.
The first is you are using innerHTML in a input element, when you want to access input element you need to get the value not the innerHTML, inputs not have this property.
The second one is that you need to pass the event on the onclick event since if you don't do it you can't cancel the submit action and then the page will be submit it automatically and reload the content. Then after you pass the event you have to apply event.preventDefault which will stop the submit for that button. Other option to avoid this problem would be possible to replace the submit button with a <button> tag or <input type="button"> since not of them will trigger the submit action.
You can see a working example https://jsfiddle.net/5c4j2opc/9/
html -> same you have
javascript
var word = document.getElementById('word'),
originalStory = document.getElementById('story'),
button = document.getElementById("submitButton");
button.onclick = function(e){
replaceStory(word.value);
e.preventDefault();
};
var replaceStory = function(userWord) {
var story = ("A " + userWord + " is now part of the story");
return originalStory.innerHTML = story;
};
You initialize wordjust in the beginning of the script. Besides, that the input value is not innerHTML, during that time, the value is empty.
As long as the return value is not set explicitly to false, the form will reload the page and overwrite any result.
Change your code:
var originalStory = document.getElementById('story'),
button = document.getElementById("submitButton");
button.onclick = function(){
var word = document.getElementById('word').value;
replaceStory(word);
return false;
};
var replaceStory = function(userWord) {
var story = ("A " + userWord + " is now part of the story");
originalStory.innerHTML = story;
};
updated fiddle
You had a couple of minor problems. The input type of the submit button should be button rather than submit. Submit does a post request and refreshes the page with the data received.
Initially you had:
var word = document.getElementById('word').innerHTML this would get the initial innerHTML which would be nothing. You have to get the inner text within word every single time the button is clicked to get the most recent text inside the textbox.
Finally, for a input node you should get .value rather than .innerHTML to get the inner text
html:
<form>
<label>Word</label><input id="word"></input>
<input type="button" value="submit" id="submitButton"></input>
</form>
<p id="story"> A {userWord goes here} is now part of the story </p>
javascript:
var word = document.getElementById('word'),
originalStory = document.getElementById('story'),
button = document.getElementById("submitButton");
button.onclick = function(){
replaceStory(word.value);
};
var replaceStory = function(userWord) {
var story = ("A " + userWord + " is now part of the story");
return originalStory.innerHTML = story;
};
I advise you to just understand Javascript first, and after then, focus on learning Jquery because it's much more easier and handy.
By the way if you want to do what you said:
You shouldn't use form tag, because you don't want to send something to server-side and you can use div tag as well instead of form tag.
<div>
<label>Word</label>
<input id="word" type="text"></input>
<button id="submitButton">Submit</button>
</div>
<span>A </span><span id="text">{here}</span><span> is now part of the story</span>
Jquery
$('#submitButton').click(function(){
txt = $('#word').val()
$('#text').text(txt);
});
Don't forget to import Jquery Package.
https://jsfiddle.net/softiran/gt8rr5pe/
You could also allow the user to change your story directly. I know this may not use an input tag, but it was very useful to me.
<div id="story">Once upon a time there was a man named
<p id="added" contenteditable="true" title="Click to change">
Bill</p>. He liked to eat tacos.</div>
I used this in a code that changed the name of the main character of a story into a user-selected name and allowed them to download the story. Hope this helps! All the user has to do is click the name "Bill" and they will be able to change the name to anything they want.

How to dynamically remove input field which is created dynamically using JavaScript

I created an input text dynamically using JS, but what if I want to remove the input field one by one dynamically using a button by calling "removeTextField()" from the JS?
Here is the JS:
<script type="text/javascript">
function addTextField(){
var element = document.createElement("input");
element.setAttribute("name", "i[]");
element.setAttribute("value", "");
element.setAttribute("class", "daters");
element.setAttribute("id", "timepicker_7");
var myvalue = document.getElementById("dispTime");
myvalue.appendChild(element);
}
</script>
...
<input type = "button" class="button2" value = "Add Time" onclick = "addTextField()"/>
The way you create the elements has a problem. You are giving the new element a hardcoded id and this means that when adding more than one, you will end with multiple elements with the same id ?(which is invalid and prone to errors when accessing the DOM)
Since you use jQuery, why not simplify your code when adding/removing elements by utilizing it?
I would use something like this
html
<input type="button" class="button2 addField" value="Add Time" />
<input type="button" class="button2 removeField" value="Remove Time" />
script
$(function(){
$('.addField').on('click', function(){
$('<input type="text">', {
name: 'i[]',
value: '',
'class': 'daters'
}).appendTo('#dispTime');
});
$('.removeField').on('click', function(){
$('#dispTime .daters').last().remove();
});
});
If you are not using jQuery then the way to remove an element
function removeTextField(){
var elements = document.getElementById('dispTime').getElementByClassName('i[]'),
last = elements[elements.length-1];
last.parentNode.removeChild(last);
}
function removeTextField() {
var timepicker = document.getElementByID("timepicker_7");
timepicker.parentElement.removeChild(timepicker);
}
you can use $.remove() for this..
refer: http://api.jquery.com/remove/
Suggestion: instead of creating elements like the one you did, create like this.
$('body').append("<input name='i[]' value='' class='daters' id='timepicker_7' />");
$('#timepicker_7').remove();
if you are creating elements on demand and want to use this element multiple times.
now you have a function which can be used as many times you want, anywhere on the page
function GetTextField() {
var field = "<input name='i[]' value='' class='daters' id='timepicker_7' />";
return field;
}
var field = GetTextField();
$('body').append(field);
$("#dispTime #timepicker_7").remove()
This is my idea(not tested):
Every time you add an input, just push it in a array, so you can remove it after:
<script type="text/javascript">
var inputStack = new Array();
function addTextField(){
var element = document.createElement("input");
element.setAttribute("name", "i[]");
element.setAttribute("value", "");
element.setAttribute("class", "daters");
element.setAttribute("id", "timepicker_7");
var myvalue = document.getElementById("dispTime");
myvalue.appendChild(element);
inputStack.push(element);
}
// Now if you want to remove, just do this
inputStack[0].remove(); // I think it'll work for example
</script>

How can I add efficiently add many fields to a form I create in JavaScript?

I've got a new page new form, and I want to hook-up to some existing server-side stuff. Right now I have this code that works, but it's sort of clunky:
// make a form
var OrderStatusSearchQueryForm = document.createElement("form");
// make first input
var Operation = document.createElement("input");
Operation.name="Operation";
Operation.value="Search";
OrderStatusSearchQueryForm.appendChild(Operation);
// make second input
var SearchFieldValue = document.createElement("input");
SearchFieldValue.name="SearchFieldValue";
SearchFieldValue.value=document.formonpage.searchString.value
OrderStatusSearchQueryForm.appendChild(SearchFieldValue);
// not shown, many more inputs like the above
// set a few important values from the form on the page
OrderStatusSearchQueryForm.submit();
I was wondering if I could write a function that would just take the a few parameters and do the same thing. The function would allow me to replace the above with this:
var OrderStatusSearchQueryForm = document.createElement("form");
stakmagic("Operation", "Search", OrderStatusSearchQueryForm);
stakmagic("SearchFieldValue", document.formonpage.searchString.value, OrderStatusSearchQueryForm);
OrderStatusSearchQueryForm.submit();
I'm not sure what you are asking. You may have answered your own question. But if you're wanting the function, here you go:
function stakmagic(name, value, form) {
var Input = document.createElement("input");
Input.name = name;
Input.value = value;
form.appendChild(Input);
}
var inps = "<input name='xx' value='xx' /><input name='xx' value='xx' /> .......etc";
<form>
<div id='mydiv'></div>
</form>
document.getElementByID('mydiv').innerHTML( inps );
This will create all of the elements simultaneously.
Obviously you could use functions, but why not let the HTML parser create the DOM for you, it's actually significantly faster than creating it yourself.
var html = '<form id="myform">' +
'<input name="Operation" value="Search" />' +
'<input name="SearchFieldValue" value="' +
document.formonpage.searchString.value +
'" /></form>';
document.getElementById("form-container").innerHTML = html;
document.getElementById("myform").submit();
Obviously even this is not optimal, as you have a bunch of hard coded html in your javascript. But
that problem was with your original javascript as well. Currently the cleanest and easiest way to do this is
javascript templates. You will be able to maintain the HTML just like it was regular HTML and use very little code to do the same thing.

Categories

Resources