How to apply javascript to element created with append()? - javascript

I have a form that appears by append(). The form contains input that need to be adjusted with with js (autocomplete function).
Here is it:
function addForm() {
<!-- function code here-->
...
html += ' <table class="form">';
html += ' <tr>';
html += ' <td>Entry product</td>';
html += ' <td><input type="text" name="product" value="" /></td>';
html += ' </tr>';
html += ' <tr>';
html += ' <td> </td>';
html += ' <td><div id="featured-product" class="scrollbox">';
html += ' </div>';
html += ' <input type="hidden" name="featured_product" value="" /></td>';
html += ' </tr>';
html += ' </table>';
$('#form').append(html);
}
$('input[name=\'product\']').autocomplete({
<!-- function code here-->
}
But autocomplete function doesn't work in this way. As I understand it is because of append(html) doesn't store the html to DOM. It works fine with usual html form, but i can't go this way. I need to create forms as described. So the questions are:
How can i apply js to element that are not in DOM? Or how can I execute this elemnt to DOM with js?
Maybe I need to use smth another like append()?
Thanks.

Put this code:
$('input[name=\'product\']').autocomplete({
<!-- function code here-->
});
after the code that appends the html. The problem is that when this bind is attempted the DOM does not contain these elements
You could also use the .on functionality to apply this:
$('input[name=\'product\']').on("autocomplete",function(){
<!-- function code here-->
});

Related

How to fix the value a html element is being split into multiple html attributes

I'm appending a value to an HTML form that is is being generated dynamically using jQuery bu the value is being split into HTML attributes. The value is a sentence. The first word is what is set as the value then the rest of the words are split into HTML attributes.
//Here is the sample data being returned
//It's in the URL provided
//Looping through the returned data and dynamically creating a form and append values to it.
$.each(data.TrainingEvaluationCard['Evaluation_Lines'].Evaluation_Lines, function(key, val) {
//Append The Table Here Witht the Data
$('tbody').append( '<tr>'+
'<td> <input class="form-control input-group-md evaluationarea"'+
'name="evaluationarea[]"'+
'value='+val.Evaluation_Area+''+
' style="font-size: 13px !important; "'+
'readonly="readonly"'+
'data-validation="required"'+
'/>'+
' </td>'+
'<td> <input class="form-control input-group-md evaluationquestion"'+
'name="question[]"'+
'readonly="readonly"'+
'value=' +val.Evaluation_Question+ ''+
'style="width: 250px;;"'+
'/>'+
' </td>'+
//Here is the result I'm getting
<input class="form-control input-group-md evaluationquestion" name="question[]" readonly="readonly" value="Were" they="" well="" distributed="" around="" the="" class?style="width: 250px;;">
I expect the Value of evaluation question to be the whole question being returned not the first word only.

Refreshing css after adding element with jQuery

I'm having problem loading custom css (twitter bootstrap) on radio input when I try to add that element using jQuery.
Here's a screenshot:
When I refresh the page the css of the radio input is loaded (next to the green arrow) but when I click to Add new sequence.
Here is the jQuery code:
$('#btn_addseq').on('click', function (e) {
e.preventDefault();
var newitem = 'some tags' +
'<input type="radio" name="is_default" value="new_' + size + '"> Default</input>' +
'some tags' ;
$("#list_sequences").append(newitem);
};
Edit:
My html for the working one:
<label class="mt-radio mt-radio-line" style="margin-top: 6px">
<input type="radio"
name="is_default" value="old_{{ $sequence->id }}" {{ $sequence->is_default ? 'checked' : '' }}>
Default
What I see in inspection:
And this is the code of the item I'm trying to add:
var newitem = '<div class="col-md-4">' +
'<div class="mt-radio-list">' +
'<label class="mt-radio mt-radio-line" style="margin-top: 6px">' +
'<input type="radio" name="is_default" value="new_' + size + '"> Default</input>' +
'</label>'+
'<a class="delete_new_seq" data-id="' + size + '"><i class="fa fa-remove" style="color: red;cursor: pointer;"></i> </a>'
'</div>' +
'</div>' ;
The rules that govern what an element looks like rely on a particular structure of HTML, in this case it looks like the css rules you use rely on either
The radio being inside a <div class="radio"> element. or;
The radio being inside a <label class="mt-radio mt-radio-line"> element.
(My guess would be the former, however its hard to know for sure without seeing all your css)
Your new control doesn't have the class specified. Add the class property to the tags like this:
var newitem = 'some tags' +
'<input type="radio" name="is_default" class="----" value="new_' + size + '"> Default</input>' +
'some tags' ;

How to insert html from a button click

I am trying to insert a form when a button is clicked but cannot find a way that does not make me put all of the HTML on one line with back slashes or many ugly lines of code. Something that does not include adding on something line jQuery or php.
In essence: How can I make this...(that is all on one line)
<script>
function newMsg() {
document.getElementById("add_message").innerHTML = "<div class=\"message\">Add Message<br>Title: <input type=\"text\" id=\"title\"><br>Text: <input type=\"text\" id=\"message\"><br><br></div>";
}
</script>
Look a little more something like this (that has good formatting and on multiple lines)
<script>function newMsg() {function newMsg() {
document.getElementById("add_message").innerHTML =
"<div class="message">Add Message<br>
Title: <input type="text" id="title"><br>
Text: <input type="text" id="message"><br><br>
</div>";
}
</script>
Simply replace the first and last " of the right hand side with ' and remove all \
like this :
document.getElementById("add_message").innerHTML = '<div class="message">Add Message<br>Title: <input type="text" id="title"><br>Text: <input type="text" id="message"><br><br></div>';
.innerHTML = '<div class="message">Add Message<br>'
+ 'Title: <input type="text" id="title"><br/>'
+ 'Text: <input type="text" id="message"><br/><br/></div>';
You can do what hamism suggested as well as concatenate if one line is too long, this way you can make your code look slightly cleaner.
You may check this fiddle:
http://jsfiddle.net/7sqha4ks/
function myFunction(){
document.getElementById("add_message").innerHTML =
'<div class="message">Add Message<br>Title: <input type="text" id="title">
<br>Text: <input type="text" id="message"><br><br></div>';
};
If you're issue is just with formatting, you can use an array of lines and the join array method like this:
var html = [
'<div class="message">Add Message<br>',
'Title: <input type="text" id="title"><br>',
'Text: <input type="text" id="message"><br><br>',
'</div>'
].join("\n");
Alternatively, you could use a templating language such as Handlebars or Jade and precompile your templates.
Alternatively, you could use a multiline string hack like this:
https://github.com/sindresorhus/multiline
If you wanna get it on separate lines like that for easier readability create your html as a variable and concatenate with the "+" symbol. Also use single quotes for any quotes inside of the main html. Something like:
var html = "<div class='message'>Add Message<br>"
+ "Title: <input type='text' id='title'><br>"
+ "Text: <input type='text' id='message'><br><br>"
+ "</div>";
document.getElementById("add_message").innerHTML = html

Not able to propagate event listener (submit for form) for element generated by(later) javascript

I have html code like -
<div class = "setup_eda_class" id = "Setup_eda">
<p>
<a> <span id="calendar_eda_form_top_x"> x </span> </a>
<br> </br>
<div id="insert_calendar_eda_form"> </div>
</p>
</div>
The div 'insert_calendar_eda_form' is inserted initially.
Javascript code
calendar_eda_add_form = function (clicked_id, arraylength){
htmlstr = "";
htmlstr += '<a> Add Events for - </a>' ;
htmlstr += '<form id="calendar_eda_add_form" action="/setupaddcalendarevent" method="POST">'
htmlstr += '<label for="start_date">Start Date</label>'
htmlstr += '<input type="text" name="start_date" />'
htmlstr += '<label for="end_date">End Date</label>'
htmlstr += '<input type="text" name="end_date" />'
htmlstr += '<br> </br>'
htmlstr += '<input type="submit" value="Add Event" />'
htmlstr += '</form>'
$("#insert_calendar_eda_form").html(htmlstr);
The form 'calendar_eda_add_form' html is created dynamically by Javascript.
HTML code for event listener
<script type="text/javascript">
$(document).ready(function(){
$('#insert_calendar_eda_form').on('submit', 'calendar_eda_add_form', function(event){
alert ('clicked add event');
event.preventDefault();
somefunction();
});
});
Calendar_eda_add_form is generated dynamically by JS. I am trying to propagate the "submit" event, but does not seem to work. Can you please help?
Missing the hash tag on the selector inside the .on()
$(document).ready(function(){
$('#insert_calendar_eda_form').on('submit', '#calendar_eda_add_form', function(event){
alert ('clicked add event');
event.preventDefault();
somefunction();
});
});
Here's a fiddle showing it working http://jsfiddle.net/ja3kaa4b/ - are you seeing any console errors in the browser?
You may be experiencing the effects of duplicate IDs. In the function calendar_eda_add_form change the ID of the form to a class and use the following code instead:
$(document).ready(function(){
$('#insert_calendar_eda_form').on('submit', '.calendar_eda_add_form', function(event){
alert ('clicked add event');
event.preventDefault();
somefunction();
});
});
UPDATE
Per the comments under the question, the above is unlikely as the form is added to the DOM only once. However, the HTML being used is not valid:
<div class = "setup_eda_class" id = "Setup_eda">
<p>
<a> <span id="calendar_eda_form_top_x"> x </span> </a>
<br> </br>
<div id="insert_calendar_eda_form"> </div>
</p>
</div>
Per the HTML spec P elements can only contain inline elements; div - the target div - is not an inline element.
Why <p> tag can't contain <div> tag inside it?
http://www.w3.org/TR/html4/sgml/dtd.html
If I understand your question, this should work:
calendar_eda_add_form = function (clicked_id, arraylength){
htmlstr = "";
htmlstr += '<a> Add Events for - </a>' ;
htmlstr += '<form id="calendar_eda_add_form" action="/setupaddcalendarevent" method="POST">'
htmlstr += '<label for="start_date">Start Date</label>'
htmlstr += '<input type="text" name="start_date" />'
htmlstr += '<label for="end_date">End Date</label>'
htmlstr += '<input type="text" name="end_date" />'
htmlstr += '<br> </br>'
htmlstr += '<input type="submit" value="Add Event" />'
htmlstr += '</form>'
return htmlstr;
// in your code I dont see where you ever do anything with `htmlstr `.
// Since you made `calendar_eda_add_form` a function, I'm assuming you meant to return `htmlstr`
// and insert the created html into your `insert_calendar_eda_form` div
// im assuming you have a reason for `clicked_id, arraylength` here but not sure what they are for
}
$(document).ready(function(){
//change this line to add the `#` and bind to `document`
$(document).on('submit','#calendar_eda_add_form',function(event){
event.preventDefault();
somefunction();
});
//put here to simulate adding form later
$('#create').click(function(){
//insert the created html into your `insert_calendar_eda_form` div
$('#insert_calendar_eda_form').html(calendar_eda_add_form);
});
});
function somefunction(){
alert ('clicked add event');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="create" value="create form"/>
<div class = "setup_eda_class" id = "Setup_eda">
<p>
<a> <span id="calendar_eda_form_top_x"> x </span> </a>
<br> </br>
<div id="insert_calendar_eda_form"> </div>
</p>
</div>

Add part of HTML code by jquery

I use ASP.NET MVC application and has the following code:
<div id="divComments">
#foreach (var comment in Model.Comments) {
<div id="comment-#comment.ID">
<div>
#comment.Username<br />
#comment.DateAdded.ToString()
</div>
<div>
#comment.Comment
</div>
<input type="button" class="deleteComment" value="Del" id="btnDel-#comment.ID" />
<br />
</div>
}
</div>
Also, I want to add div block with id="comment-X" via jquery. I do it the following way:
$('#divComments').append('<div id="comment-' + resp.Result.ID + '"><div>' + $('#Username').val() + '<br />' + resp.Result.date + '</div><div>' + comment + '</div><input type="button" class="deleteComment" value="Del" id="btnDel-' + resp.Result.ID + '" /><br /></div>');
Is it possible to move it to any PartialView/Html file and work with it in both places - cshtml (inside my foreach) and jquery?
This HTML part is only an example; this part can be much more bigger.
The first section is fine, if you want to move to a partial view you can have the partial view setup the html you want with a viewmodel passing in the information you want populated. You would then call that controller action and then append the result to the divComments block.
This would allow you to add complicated pieces of html without a messy string, etc.

Categories