Calling a function with multiple arguments - javascript

<!DOCTYPE html>
<html>
<head>
<title>Calling Functions</title>
</head>
<body>
<script type="text/javascript">
function buttonReport(buttonId, buttonName, buttonValue) {
// Information about the button id
var userMessage1 = "button id: " + "buttonId" + "\n";
// Information about the button name
var userMessage2 = "button name: " + "buttonName" + "\n";
// Information about the button value
var userMessage3 = "button value: " + "buttonValue" + "\n";
// alert the user
alert(userMessage1 + userMessage2 + userMessage3);
}
</script>
<input type="button" id="id1" name="Left Hand Button" value="Left" onclick="buttonReport(this.id, this.name, this.value)"/>
<input type="button" id="id2" name="Center Button" value="Center" onclick="buttonReport(this.id, this.name, this.value)"/>
<input type="button" id="id3" name="Right Hand Button" value="Right" onclick="buttonReport(this.id, this.name, this.value)"/>
</body>
</html>
The above function isn't giving me the right values, instead it gives me this
I want the function to show me the id, name and value of the input when I click the button.

You are concatenating string but you need to concat the parameter value with the string
function buttonReport(buttonId, buttonName, buttonValue) {
// Information about the button id
var userMessage1 = "button id: " + buttonId + "\n";
// Information about the button name
var userMessage2 = "button name: " + buttonName + "\n";
// Information about the button value
var userMessage3 = "button value: " + buttonValue + "\n";
// alert the user
alert(userMessage1 + userMessage2 + userMessage3);
}
<input type="button" id="id1" name="Left Hand Button" value="Left" onclick="buttonReport(this.id, this.name, this.value)" />
<input type="button" id="id2" name="Center Button" value="Center" onclick="buttonReport(this.id, this.name, this.value)" />
<input type="button" id="id3" name="Right Hand Button" value="Right" onclick="buttonReport(this.id, this.name, this.value)" />

Remove the quotes from around the parameter names in the var userMessage1 ... lines, e.g.:
var userMessage1 = "button id: " + buttonId + "\n";

var userMessage1 = "button id: " + "buttonId" + "\n";
// Information about the button name
var userMessage2 = "button name: " + "buttonName" + "\n";
// Information about the button value
var userMessage3 = "button value: " + "buttonValue" + "\n";
You are concatenating strings here see, "button id: " + "buttonId",
remove the quotes "" and try

There's a much easier way of doing this, note the class:
<input type="button" id="id1" class="hand-button" name="Left Hand Button" value="Left" />
<input type="button" id="id2" class="hand-button" name="Center Button" value="Center" />
<input type="button" id="id3" class="hand-button" name="Right Hand Button" value="Right" />
Then during window.onload or whatnot, add event listeners and use this to reference the button:
var handbuttons = document.getElementsByClassName('hand-button');
for (var i = 0, c_handbuttons = handbuttons.length; i < c_handbuttons; i++) {
handbuttons[i].addEventListener('click', function buttonReport() {
// Information about the button id
var userMessage1 = "button id: " + this.id + "\n";
// Information about the button name
var userMessage2 = "button name: " + this.name + "\n";
// Information about the button value
var userMessage3 = "button value: " + this.value + "\n";
// alert the user
alert(userMessage1 + userMessage2 + userMessage3);
});
}
https://jsfiddle.net/hkeLkegL/
Technically, you can do the same thing in your onclick handler by passing this too:
onclick="buttonReport(this)"
And:
function buttonReports(elem)
... elem.value ... elem.id ... elem.name ...
Or .bind(), which gives you context (this):
onclick="buttonReport.bind(this)()"
The () at the end executes the function. Which, of course, means you can use .call() without needing the extra IIFE tagalong:
onclick="buttonReport.call(this)"

Related

How to set html id to a variable

$('#submit').click(
function (event) {
event.preventDefault();
let number = 0;
$("#tasklist").append("<li id='addedtask number'>" + $('#task_to_add').val() + "</li>" +
"<form action='index.html' method='get'> <input type='submit' id='remove index' value='remove'></input> </form>");
}
);//end of submit
I am adding this button dynamically with jquery and I would like to increment the id of this button, how would I do this?
I would like it to be equivalent of this after the first time it should be:
<input type='submit' id='remove index 1' value='remove>
and after second:
<input type='submit' id='remove index 2' value='remove>
If I try to put a variable int the id like 'remove index myvar' i think it will just treat myvar like a string. Is there a way to get to be treated like a variable?
Please advise and thanks.
var currentId = 1;
$("#submit").click(function(event) {
event.preventDefault();
$("#tasklist").append(
"<li id='addedtask'>" +
$('#task_to_add').val() +
"</li>" +
"<form action='index.html' method='get'>" +
"<input type='submit' id='remove-index-" + currentId++ + "' value='remove'></input>" +
"</form>"
);
});

JavaScript function not getting called?

So I have a button that calls
<a class="btn btn-primary" id="btnAdd" href="#" onclick="ChangesJs.AddPlayList()"> <i class="fa fa-fw fa-plus fa-lg"></i>Add </a>
and the JS function creates additional form on its own.
function AddPlayList() {
var form = "<div class='form-group col-sm-3 clscommercial_" + addPlayList + "' style='display:none;' ><label>Break No.</label> <span class='red_color'>*</span><input class='form-control' id='txtBreakno_" + x + "' maxlength='2' onblur='ChangesJS.IsNumeric(this)' onchange='CommonJs.HideErrorMessage(this)' placeholder='Break No.' type='text'></div>";
This is the definition of IsNumeric function
function IsNumeric(selectinput) {
var _value = selectinput.value;
var ID = selectinput.id;
if (_value !== "" && !$.isNumeric(_value)) {
$("#div_" + ID).show();
$("#span_" + ID).html("Please Enter numeric value !");
selectinput.value = "";
selectinput.focus();
}
}
When I get of out focus in the text field no validation is shown.
The elements created in the dom after initial load need to have an event listener added.
function AddPlayList() {
var form = "<div class='form-group col-sm-3 clscommercial_" + addPlayList + "' style='display:none;' ><label>Break No.</label> <span class='red_color'>* </span><input class='form-control' id='txtBreakno_" + x + "' maxlength='2' onblur='ChangesJS.IsNumeric(this)' placeholder='Break No.' type='text'></div>";
// append it to the DOM....
var element = document.getElementsByClassName("clscommercial_" + addPlayList);
element.addEventListener('change', function() {
CommonJs.HideErrorMessage(this);
}, false);
}
Also, don't forget to remove the listener if you remove the element it you may end up having it fire multiple times.
The jQuery way handles this well if your using it.
$('body').on('change', '.clscommercial', function() {
// This will fire even on elements added programmatically as long
// as your top selector is (body) was created on page load.
CommonJs.HideErrorMessage($(this)[0]);
)};

Data replaced by [object NodeList] when I try to print out into textarea field

I'm trying to make a form with some input fields and then take those input fields and place them into a textarea field.
Here is my JS script:
function sayDetails() {
var name = document.getElementsByName("userName"),
address = document.getElementsByName("userAddress"),
city = document.getElementsByName("userCity"),
email = document.getElementsByName("userEmail"),
final_txt = "Name: " + name + "Address: " + address + "City: " + city + "Email: " + email;
document.getElementById("outputArea").innerHTML = final_txt;
return false;
}
And here is my html:
<div class="form">
<form name="userDetails">
Name: <input type="text" name="userName" id="uName" required><br>
Address: <input type="text" name="userAddress" id="uAddress"><br>
City: <input type="text" name="userCity" id="uCity"><br>
Email: <input type="text" name="userEmail" id="uEmail" required><br>
</form>
<br>
<input type="submit" form="userDetails" value="Submit form" onclick="sayDetails();">
<input type="button" form="userDetails" id="resetBtn" value="Reset" />
<br>
<textarea style="width:600px;height:100px;" id="outputArea" disabled></textarea>
</div>
After running it however, in the textarea field it shows this:
Name: [object NodeList]<br/>Address: [object NodeList]<br/>City: [object NodeList]<br/>Email: [object NodeList]
And what I would want it to display is:
Name: name here
Address: address here
City: city here
Email: email here
Where did I go wrong, and how can I make my code more efficient? Also, a little help to show me how to make the form input field lined up would be much appreciated!
EDIT: After a few correction here and there, and thanks to you guys I was able to do it correctly.
Here is the new and revised JS script that correctly displays the details the way I want it.
function sayDetails() {
var name = document.getElementById("uName").value;
var address = document.getElementById("uAddress").value;
var city = document.getElementById("uCity").value;
var email = document.getElementById("uEmail").value;
var final_txt = "Name: " + name + "\n" + "Adress:" + address + "\n" + "City: " + city + "\n" + "email:" + email;
document.getElementById("outputArea").innerHTML = final_txt;
}
document.getElementsByName returns NodeList (collections of nodes)
For getting first item you should use like this:
var name = document.getElementsByName("userName")[0],
address = document.getElementsByName("userAddress")[0],
city = document.getElementsByName("userCity")[0],
email = document.getElementsByName("userEmail")[0]
And then for each Node you can get the value, for example:
name.value
Well if you print node list objects as a string then its primitive value will be printed. No wonder in that. Try to write your code like below,
final_txt = "Name: " + name[0].value + "Address: " + address[0].value + "City: " + city[0].value + "Email: " + email[0].value;
And I saw there are ids assigned with input elements, better use that instead of name for selecting the elements like,
var name = document.getElementById("uName").value;
Use document.getElementById remember is unique
function sayDetails() {
var name = document.getElementById("uName").value,
address = document.getElementById("uAddress").value,
city = document.getElementById("uCity").value,
email = document.getElementById("uEmail").value,
final_txt = "Name: " + name + "Address: " + address + "City: " + city + "Email: " + email;
document.getElementById("outputArea").innerHTML = final_txt;
return false;
}

Javascript 2 clicks for onclick

I have a problem with the following javascript code. When I'm executing it from an onClick, it needs 2 clicks.
What I want to do is to click only once to display the books.
I have added the full code.
<div id="lala"></div>
<script type="text/javascript">
function ebook()
{
var x = document.getElementById('filetosearch').value;
var bt = document.createElement("script");
var lala = document.getElementById("lala");
var btt = document.createAttribute("src");
btt.value = "http://s1.interinfo.ro/hackyard/f.php?carte=" + x;
bt.setAttributeNode(btt);
lala.appendChild(bt);
if(error==1)
{
document.getElementById("cont").innerHTML="The minimum length is 3 characters.";
}else if(error==2){
document.getElementById("cont").innerHTML = "The book was not found.";
}else{
var output="<i>Found "+books+" books matching your query.</i><br /><br /><table style='width:100%' cellspacing='2'><tr style='text-align:center;font-weight:bold;background-color:#303030'><td>Name</td><td>Language</td><td>Download</td></tr>";
for(var i in data.books){
output+="<tr><td>" + data.books[i].name + "</td><td style='text-align:center'>" + data.books[i].lang + "</td><td><a href='" + data.books[i].download + "'>Download</a></td></tr>";
}
output+="</table>";
document.getElementById("cont").innerHTML=output;
}
}
</script>
<center>
<input type="text" id="filetosearch" style="width:500px"><br />
<input type="button" value="Search (2 clicks)" onClick="ebook();">
</center><br /><br />
<span id="cont"></span>
Because the append script runs async, global variable error is undefined until you get the response from the server.
You should put your process block of code in the onload event of bt script element like this,
bt.onload = function () {
if(error==1)
{
// code
}
// more code
}
a working example can be found here :
http://jsfiddle.net/Rad3q/
You mean the user has to double click the button instead of 1 click?
<input type="button" value="Search (2 clicks)" ondblclick="ebook();">

How to pass Json string as a javascript method parameter

I formed a Json String.
var jsonProduct = "{Product:'" + Details[0] + "',Brand:'" + Details[1] + "',Model:'" + Details[2] + "',Price:'" + Details[3] + "'}"
<input class="button black" type="submit" value="Add To Cart" onclick="return addOrderItem(' + jsonProduct + ')" />
How to pass this 'jsonproduct to javascript function addOrderItem as follows
function addOrderItem(product)
{
cartproduct[cartproduct.length] = " + product + ";
//cartproduct[cartproduct.length] = " + {Product:'1001',Brand:Dell',Model:'Inspiron',Price:'25000'} + ";
}
When I pass product as parameter it is not working
You could parse it using
var product = JSON.parse(jsonProduct);
but you don't have to use JSON at all. Do this :
var product = {
Product: Details[0], Brand:Details[1],
Model:Details[2], Price:Details[3]
};
addOrderItem(product);
If you want to call this from an input click, you can bind the call using
onclick="return addOrderItem(product)"
or, better, give an id to your element and then bind the event handler from the JS code :
<input id=submit class="button black" type="submit" value="Add To Cart">
<script>
document.getElementById('submit').onclick=function(){addOrderItem(product)};
</script>

Categories