Dynamically building a button with an onClick - javascript

I am dynamically building a button in JavaScript, this will include an onClick event. The onClick event needs to focus a field which is stored in a variable.
I couldn't find a way of using the field variable itself, so instead decided to try using the field.selector property from the JQuery object, this WILL contain " ".
Here is a code snippet of the construction as it stands.
InvalidField.prototype.getMessageStructure = function(){
var structure = '<div class="invalidMessage"><span>' + this._message + '</span>
<button class="inputButton"
Value="Go To Field"
onclick=\'goToFieldFromAlert($(\'' + this._field.selector + '\'))\'
/>
</div>';
return structure;
};
This is outputting:
<button class="inputButton"
value="Go To Field"
onclick="goToFieldFromAlert($(" input[name="applicant.email" ]'))'="">
</button>
As you can see, the quotations will not be out put correctly and so break on click.
Can anyone foresee a better way of performing this function, or correcting the quotations? I see from this SO Answer that the DOM doesn't respect the quotations which is what is currently causing me the issue.
Kind Regards.

As I mentioned in comment, avoid using onclick at all. jQuery event handlers are far more flexible (and support multiple event handlers).
1) Inject the fieldname (only, not the jQuery selector) into a data- attribute:
InvalidField.prototype.getMessageStructure = function(){
var structure = '<div class="invalidMessage"><span>' + this._message + '</span>
<button class="inputButton"
value="Go To Field" data-field="' + this._field.name + '"/>
</div>';
return structure;
};
2) Use a delegated event handler to get all clicks on inputButtons with less overhead. Extract the field name and do the jQuery where it belongs:
$(document).on('click', '.inputButton', function() {
var $button = $(this);
var field = $button.data('field');
goToFieldFromAlert('input[name="' + field + '"]');
});

You should create element using jQuery. This is much cleaner and error free approach
An example with your code
InvalidField.prototype.getMessageStructure = function(){
var structure =
$('<div></div>').append(
$('<span></span>').text(this._message)
);
structure.append(
$('<button></button>')
.addClass('inputButton')
.text("Go To Field")
.click(function(){
goToFieldFromAlert($(this._field.selector));
})
);
return structure;
};

The following example will dynamically add buttons:
hello.forEach( function(result) {
var card = document.createElement("input");
card.type = "button";
card.onclick = function() {
newcard( result );
}
card.value = value; // some value
card.style.backgroundColor="#5ABC7B";
document.body.appendChild(card);
});

Related

Why button not created properly in JS function?

I create button dynamically in my JS function and the put created button to the DOM.
Here is the code:
var button = '<button id="btnStrView" type="button" onclick=' + parent.ExecuteCommand(item.cmdIndex) + ' class="button_air-medium">'+
+'<img id="streetView" class="miniToolbarContant" src="../stdicons/streetview-icon.png">'
+'</button>'
$( "#tdStrView" ).append(button);
When I display the creted dynamically button in consle I see this:
"<button id="btnStrView" type="button" onclick=undefined class="button_air-medium">NaN</button>"
it seems that but not created properly the onclick is undefined and img tag is missing.
any idea what I do wrong? Why image button not created properly?
UPDATE:
I tryed to add double quotes to the onclick event:
onclick="' + parent.ExecuteCommand(item.cmdIndex) + '"
and the created button is:
"<button id="btnStrView" type="button" onclick="undefined" class="button_air-medium">NaN</button>"
the onclick is still undefined.
You need to add double quotes.onclick will look like this onclick ="yourFunction()"
onclick="' + parent.ExecuteCommand(item.cmdIndex) + '"
// add double quotes in onClick and if you are getting NaN in place of image,
// it means that it is trying to add numbers. I'm not sure yet why this is happening, but
// to fix that, add extra string in second line. like this. and then console button.
var button = '<button id="btnStrView" type="button" onClick="alert(7)" class="button_air-medium">'+
+'' +'<img id="streetView" class="miniToolbarContant" src="../stdicons/streetview-icon.png">'
+'</button>'
While this code is a lot more verbose, it is more readable and less error prone.
const button = document.createElement('button');
button.id = 'btnStrView';
button.type = 'button';
button.className = 'button_air-medium';
button.addEventListener('click', event => {
parent.ExecuteCommand(item.cmdIndex);
});
const img = document.createElement('img');
img.id = 'streetView';
img.className = 'miniToolbarContant';
img.src = '../stdicons/streetview-icon.png';
button.appenChild(img);
$( "#tdStrView" ).append(button);

append() in jquery does'nt append file second time

I have defined an input of type file and a hidden form below it,
<input type="file" name="attachment0" id="attachment0" custom-on-change="uploadfile" ng-show="attachFile" multiple/>
<form class="hidden" id="myForm" method="post" enctype="multipart/form-data" action="SupportRequest">
</form>
"custom-on-change" is an angular directive that calls the function uploadfile() after choosing files. My javascript looks as shown below
var form = $('#myForm');
var n=0;
$scope.attachFile = true;
$scope.uploadfile = function() {
if(n == 0){
var filein = $('#attachment0');
form.append(filein);
$('#attachment0').test();
}
else
{
if(n==1){
var temp = "attachment0" + '_' + n;
var file_in = $('#'+temp);
form.append(file_in);
$('#'+temp).test();}
}
};
$.fn.test = function() {
return this.each(function(){
n++;
$(this).attr('id', this.id + '_' + n);
$(this).attr('name', this.name + '_' + n);
});
};
Am trying to append files twice to the form myForm. When i choose files second time, even after appending, i see that the previously appended input with id="attachment0" is not present in myForm and the input of id="attachment0_1" is present in the form.
Here am trying to upload multiple files multiple times, that is why am dynamically changing the id of the input in test().
I want both input with id attachment0 and attachment0_1 in myForm.
Does anyone know how this can be fixed? And explain this behavior too.
Change your code from form.append(filein) to form.append($('#attachment0').clone()).
It work then. You should use .clone() method to copy elements .
.append() just moves the element from one place to another but for copying first create the copy of the element using .clone() and then append it to your form
looks like in test function you are replacing id,
$(this).attr('id', this.id + '_' + n);
Would is not be better to use ng-repeat? Something like this:
Controller:
$scope.files = [...] // list of files
$scope.uploadfile = function() {
// So stuff to get the file
$scope.files.push(filein);
};
Html:
<!-- Inside the form -->
<div ng-repeat="file in files">{{file}}</div>

Return a value created in an event handler inside a function from the same function

I have an input box and a go button. When the user clicks the go button I want to compare the inserted value with another value. I am trying to acquire the input value inside a function like so
function getInput(){
var entry ='';
$('button.go').on('click',function(){
var entry = $(this).siblings('.input').val();
//return entry
})
return entry
}
Basically I want to return the var entry that has an input value, so I could compare the values later in the code
var input = getInput() // this should have input value
is input > othervalue
I call getInput inside document.ready()
You are doing everything right . There are some scope related issues that is not helping you to get the expected result . My suggestion would be to define othervalue variable as global and check it inside the function like this
function getInput(){
$('button.go').on('click',function(){
var entry = $(this).siblings('.input').val();
if(entry>othervalue) //your code
});
}
I am not sure why you are binding dynamic click event inside a function . If there is nothing else you need to do here except this part, then wrap this piece of code inside document.ready.
I would suggest to declare your var entry =''; globally and assign it before comparing.
var entry="";
$('button.go').on('click',function(){
entry = $(this).siblings('.input').val();
});
//do the comparing..
You should do the comparing, after delegating the click function, inside the function.
var entry = "";
$('button.go').on('click', function(){
var entry = $(this).prev('.input').val();
if (entry < x)
// Do something
});
It remains unclear to me what you want to accomplish.
I made some code that might be somewhere near what you want.
jQuery().ready(function()
{
var startValue = $('input[name="the_input"]').val();
$('form').submit(function()
{
var currentValue = $('input[name="the_input"]').val();
$('body').append('<br />' + startValue + ' - ' + currentValue + ' = ' + (startValue - currentValue));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="#" method="post">
<input type="text" value="10" name="the_input" /><br />
<input type="submit" value="go!" />
</form>

Calling function from button not working for html created using javascript

I am using javascript to create html page , but not able to call some function on button click .
var alernative = "plot1";
var buttonvalue= "mybutton";
function callme()
{alert("hello");}
$('#' + alernative).html('<div><input style="float:right;" type="button" value="' + buttonvalue+ '" onclick="' + callme() + '";></div>');
In above code , creating a button and giving its value and calling function onclick of button , but when the page loads it shows alert (that should not happen) and it is not alerting on button click .
Hoping for Suggestion or some help .
You need to pass the function name as a part of the string:
$('#' + alernative).html('<div><input style="float:right;" type="button" value="' + buttonvalue+ '" onclick="callme();"></div>');
It is a bad practice to write HTML with strings, DOM exists for one reason!
var input = $('<input/>', {
type: "button",
style: "float: right",
value: buttonValue
}),
element = $('<div/>').append(input);
input.click(function () {
callme();
});
$('#test').html(element);

Javascript append/remove elements

I have one question. Is possible delete <span> element added with javascript append?
When i try remove added span then nothing happens.
Like this:
<script type="text/javascript">
$(document).ready(function(){
$('#SelectBoxData span').click(function(){
var StatusID = this.id;
var StatusIDSplit = StatusID.split("_");
var StatusText = $('#SelectBoxData #' + StatusID).text();
$("#SelectBox").append('<span id=' + StatusID + '>' + StatusText + '</span>');
$("#SelectBoxData #" + StatusID).remove();
InputValue = $("#StatusID").val();
if(InputValue == ""){
$("#StatusID").val(StatusIDSplit[1]);
}
else{
$("#StatusID").val($("#StatusID").val() + ',' + StatusIDSplit[1]);
}
});
$('#SelectBox span').click(function(){
var StatusID = this.id;
$("#SelectBox #" + StatusID).remove();
});
});
</script>
<div id="SelectBoxBG">
<div id="SelectBox"><div class="SelectBoxBtn"></div></div>
<div id="SelectBoxData">
<span id="StatusData_1">Admin</span>
<span id="StatusData_2">Editor</span>
<span id="StatusData_4">Test 1</span>
<span id="StatusData_6">Test 2</span>
</div>
<input type="hidden" id="StatusID" />
</div>
Please help me.
Thanks.
Yes, you can delete them. However, you can't add click event handlers to them before they exist. This code:
$('#SelectBox span').click(function(){
var StatusID = this.id;
$("#SelectBox #" + StatusID).remove();
});
will only add a click event handler to <span> elements inside of #SelectBox at the time the code is run (so, based on your provided HTML, zero elements). If you want the event handler to react to dynamically added elements then you need to use a technique called event delegation, using the .on() function:
$('#SelectBox').on('click', 'span', function() {
$(this).remove(); // equivalent to the code you had before
});

Categories

Resources