I'm having a kind of problem that I think is related to how I generate my HTML... I use a JavaScript function to generate some HTML, but then it begins to misfunction... let me first paste some of my code
First, my raw HTML
<div id="effect">
<label for="s_effect">Effect: </label>
<select name="s_effect" id="s_effect" onchange="ne();">
<option value="">Select your Effect</option>
</select>
<div id="effect_description"></div>
<div id="effect_options"></div>
</div>
Then, I have a function that loads "s_effect" based on an array (that's fine and working, np).
Then, my ne() (new effect) function:
function ne(){
reset();
e = g('s_effect');
if(newEffect(e.options[e.selectedIndex].value)){
console.log("new effect created");
updateScreen();
}
}
It basically "resets" parts of the screen (error tracking and that, stuff not related with my problem), then calls to updateScreen() (note: g function is just a synonym for document.getElementById)
It goes to this function (sorry it's a lot of code...)
function updateScreen(){
if(project.effect instanceof Effect){
lock("instant");
lock("event");
showDescription();
generateOptions();
}else if(project.effect == null){
unlock("instant");
unlock("event");
}
if(project.check()){
generateButton();
}else{
npButton();
}
}
That basically, locks some part of the window, then get some HTML on calls below.
generateDescription(), the part is giving trouble, does the following:
function generateOptions(){
g('effect_options').innerHTML = '';
effectID = project.effect.calculateId();
if(effectID === false)
return false;
g('effect_options').innerHTML = project.effect.parameters.HTMLOptions;
return true;
}
It calls to an object attribute that basically dumps some HTML code:
<div>
<label for="1_color">Color: </label><input type="color" id="1_color" name="1_color" onchange="updateColor('1_color');" value="#FFFFFF">
<input type="text" name="1_color_rgb" id="1_color_rgb" onchange="updateColor('1_color_rgb');" value="#FFFFFF">
</div>
<div id="extra"></div>
<div>
<input type="button" value="Add Node" onclick="addNode();">
</div>
Finally, addNode() makes an innerHTML += [new div on "extra"] but increasing the number (2_color, 2_color_rgb, and so on).
function addNode(){
var count = ++(project.effect.parameters.colorCount);
g('extra').innerHTML +=
'<div><label for="' + count + '_color">Color: </label><input type="color" id="' + count + '_color" name="' + count + '_color" onchange="updateColor(\'' + count + '_color\');" value="#FFFFFF" />' +
'<input type="text" name="' + count + '_color_rgb" id="' + count + '_color_rgb" onchange="updateColor(\'' + count + '_color_rgb\');" value="#FFFFFF" /></div>' +
}
To this point everything is working fine, even "updateColor" works (it updates the value of each input so you can choose a color by filling any input).
The problem comes when I modify any x_color or x_color that has been added via button... It adds a new "node" but restarts the values of previous inputs.
I debugged it, and by the point is doing the adding, the innerHTML of "extra" shows all inputs with "#FFFFFF" values (initial), but on the screen, the values are right...
Any help with this may be appreciated.
PS: I'm using chrome.
Thank you!
Just to clarify, as #Forty3 answered, the problem was the fact that I was modifying the innerHTML each time, making my browser to re-render extra each time.
As he suggested, I edited my function, now looks like
function addNode(){
var count = ++(project.effect.parameters.colorCount);
var nDiv = document.createElement("div");
nDiv.innerHTML = "whatever I was putting...";
g('extra').appendChild(nDiv);
}
Now it works fine.
Thank you all for the support.
The issue, it appears, is that by reassinging the .innerHTML property of the g('extra') DOM element, you are telling the browser to re-render the element based on the HTML -- not the DOM elements and values contained within.
In other words, when you add a color, the g('extra').innerHTML gets updated with the new HTML to render an additional color selection block (i.e. 2_color). When a user then picks a new color, the browswer will update the value for the 2_color DOM element but doesn't necessarily update the innerHTML property for g('extra'). Then, when another color block is added, the innerHTML is updated once more and the browser re-renders it thereby "resetting" the values.
Instead of constructing the additional controls using HTML string, use DOM manipulation (e.g. .createElement() and .append()) in order to add your new options.
Related
I am trying to get the element with the ID 1a, 2a, 3a etc. according to whenever the function is run.
It then compares that elements value (using jQuery) with the value of the input where the function is wrong
It brings up an error saying:
TypeError: var1.toUpperCase is not a function. (in 'var2.toUpperCase()','var1.toUpperCase' is undefined)
Any help would be appreciated.
Thanks
(UPDATE usually there would be text in questionNumber like: 1, 2, 3 etc every time the another function is run.)
EDIT: Every time a different function is run, questionNumber is increased by 1. I save questionNumber's text in a variable called word. I then add the letter a to that variable. Then, I get the element that has ID of the variable word, then compare it's contents to the value of the input, but the comparison is uppercase to avoid problems. If they are equal, the input is replaced with a div with green text. Hope this makes it clearer.
function textVerify(item) {
var word= document.getElementById(($('#questionNumber').text()+'a'));
if (item.value.toUpperCase() === word.toUpperCase()){
item.style.color = "green";
$( item ).replaceWith( "<div style='color:green;'>"+word+"</div>" );
main()
} else {
item.style.color = "black";
}
<span class="ihide" id="questionNumber"></span>
<p id="1a" class="ihide">Seven</p>
<input id="1" name="Seven" type="text" value="" onkeyup="textVerify(this)" autofocus="">
The var word is p tag, so you need to get the inner text of it and compare it with the input text. Also, when replacing it, access the text() property of it. See below. main() is commented out here, but you can keep as per the need.
function textVerify(item) {
var word = document.getElementById(($('#questionNumber').text() + 'a'));
if (item.value.toUpperCase() === $(word).text().toUpperCase()) {
item.style.color = "green";
$(item).replaceWith("<div style='color:green;'>" + $(word).text() + "</div>");
//main()
} else {
item.style.color = "black";
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<span class="ihide" id="questionNumber">1</span>
<p id="1a" class="ihide">Seven</p>
<input id="1" name="Seven" type="text" value="" onkeyup="textVerify(this)" autofocus="">
In your code ($('#questionNumber').text()+'a') this part returns just 'a', as text of the id questionNumber is nothing.
And in your HTML there is no such id. I think you need to make this changes to your HTML code:
<span class="ihide" id="questionNumber">1</span>
This should work.
EDIT: Also, can you please share the JS code associated with 'item', there can be an error in that part too.
My starting html looks like this:
<label> Names: </label><br>
<input type="text" class="form-control name" placeholder="name1" id="name1" name ="name1"><br>
and i have a variable that captures the html:
var html = "<label> Names: </label><br><input type=\"text\" class=\"form-control name\" placeholder=\"name1\" id=\"name1\" name =\"name1\"><br>"
Then I have an onchange operator that performs a couple functions when the first row has text in it. the .onchange is picked up fine the first time and the subsequent functions are run. I end up with an additional row:
for (n = 1; n < inputLength+1 ; ++n) {
var test2 = document.getElementById(dude+n);
test2.onchange = forFunction
}
function forFunction() {
for (m = 1; m < inputLength+1 ; ++m) {
var test = document.getElementById(dude+m)
if (test.value != "") {
var txt = "<input type=\"text\" class=\"form-control name\" placeholder="+dude+(m+1)+" id="+dude+(m+1)+" name="+dude+(m+1)+"><br>";
document.getElementById('group_names').innerHTML = updateHTML(txt);
//function updateHTML(txt)
}
}
}
var html = "<label> Names: </label><br><input type=\"text\" class=\"form-control name\" placeholder=\"name1\" id=\"name1\" name =\"name1\"><br>"
function updateHTML(txt) {
html = html + txt;
return html;
}
The issue is that after all that completes i end up with two input rows as desired: name1 and name2. However, when i enter text in those fields for a second time, the .onchange is not picked up. but the elements are there in the html when i inspect and view the html.
Also, when i
console.log(inputFormDiv.getElementsByTagName('input').length);
the length of the inputs increases from 1 to 2 after i first run functions (upon the first time i change the value in my input field) so that is getting recognized correctly, just not the .onchange.
thoughts?
The onchange will only work if added to the attribute on the html and the user clicks out of a textbox e.g:
<input onchange="forFunction()" type="text" class="form-control name" placeholder="name1" id="name1" name ="name1">
To add the onchange event in JavaScript code. Add the change event to the addEventListener e.g:
var test2 = document.getElementById(dude+n);
test2.addEventListener('change', forFunction, false)
However if you want the event to fire whilst the user is types a key then use the keypress event. e.g:
var test2 = document.getElementById(dude+n);
test2.addEventListener('keypress', forFunction, false
A basic example: https://jsfiddle.net/xrL6y012/1/
Instead of .innerHTML = html + text do .insertAdjacentHTML('beforeend', text), that way you keep the original html (and events binding).
Edit: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
I had the same problem, it seems like modifying the HTML will never work, regardless of how you do it (.innerHTML or .insertAdjacentHTML()).
The only way that worked for me is to append a child instead of editing the HTML, like so:
const span = document.createElement('span');
span.innerHTML = 'text and <b> html stuff </b>';
initialElement.appendChild(span);
And if you actually need to insert just pure text, then this works:
initialElement.append('just text');
Hope that helps.
I have this menu, statically, it is as follows:
<div class="dropdown col-sm-3">
<button type="button"
class="btn btn-select btn-block"
data-toggle="dropdown">Plane <span class="caret"></span>
</button>
<ul class="dropdown-menu dropdown-menu-select" id="plane">
<li><label class="dropdown-radio"> <input type="radio" value="3" name="plane"> Plane: A360 </label></li>
<li><label class="dropdown-radio"> <input type="radio" value="2" name="plane"> Plane: AR45 </label></li>
<li><label class="dropdown-radio"> <input type="radio" value="1" name="plane"> Plane: A380 </label></li>
</ul>
</div>
...
<script>
$('.dropdown-radio').find('input').change(function() {
var dropdown = $(this).closest('.dropdown');
var radioname = $(this).attr('name');
var checked = 'input[name=' + radioname + ']:checked';
//update the text
var checkedtext = $(checked).closest('.dropdown-radio').text();
dropdown.find('button').text( checkedtext );
//retrieve the checked value, if needed in page
var thisvalue = dropdown.find( checked ).val();
console.log( thisvalue );
});
</script>
This version worked: the user could select one (and only one) option, and the option would then be displayed in the main button. I have now created this same menu dynamically with data from a MySQL database.
<script>
var socket = io.connect('http://localhost:3000');
socket.on('sess', function(message) {
if(message == 0){
alert('No planes associated.');
}else{
for(var i = 0; i < message.length; i++){
$('#session').prepend( '<li><label class="dropdown-radio" > <input type="radio" value="'
+ message[i].idSession + '" name="session"> Session: '
+ message[i].idSession + ' </label></li>');
}
}
});
</script>
Here the menu still drops down but now the user can check as many radios as they want and the first script isn't activated (nothing appears in the console). I have tried putting the second script both before and after the previous one, both give the same results.
Is there a workaround for this? I'm new to Javascript (jQuery) and its sensibilities.
Thanks
What you want is to bind the change event to a higher on hierarchy element rather then directly at the inputs that didn't exist yet:
$('#plane').on('change', 'input', function() {
var dropdown = $(this).closest('.dropdown');
var radioname = $(this).attr('name');
var checked = 'input[name=' + radioname + ']:checked';
//update the text
var checkedtext = $(checked).closest('.dropdown-radio').text();
dropdown.find('button').text( checkedtext );
//retrieve the checked value, if needed in page
var thisvalue = dropdown.find( checked ).val();
console.log( thisvalue );
});
Doing so, you are binding the change event to the parent div, so doesn't matter how you modify its children on a later moment, it will always fire an event for it if the target element was an input (second function argument).
You don't need to execute this script AFTER the inputs were loaded, just go with your initial approach on dynamically loading content but tweak that change with the on('change' version.
I've combined my comments to an answer for easier reading/for anyone else looking at this.
The first script runs once inline of the page load and due to the asynchronous call to your database, that means it doesn't find anything to bind change to and then the script is never run again. You'll need to update your script so that it is run again after the new radio buttons have all been loaded into the DOM (this is after in time, not on the page).
Consider saving your first script to a function and calling it from your database call success, post rendering your radio buttons. You may need to use .off('change') also to remove any existing change bindings before creating new ones.
With regards to your radio buttons allowing multiple selected, as long as they share a name then they shouldn't allow multiple as per the documentation.
new here and would like some help.
I'm working on a project and where I created some elements with dynamically generated ids but I can't tailor my existing code to work with dynamic ids.
Here is my HTML:
And here is my working JS script:
$('#headline1').keyup(updateCount).keydown(updateCount);
document.getElementById("headline1").addEventListener("change", updateCount);
function updateCount() {
var cs = $(this).val().length;
$('#countHeadline1').text(cs);
cs = $(this).val();
$('#headlineText1').text(cs);
}
And here is what I tried among other solutions but nothing seems to work:
var c = 1,
var headline1 = "headline1" + c;
var countHeadline1 = "countHeadline1" + c;
var headlineText1 = "headlineText1" + c;
$('#' + headline1).keyup(updateCount).keydown(updateCount);
document.getElementById("headline1" + c).addEventListener("change", updateCount);
function updateCount() {
var cs = $(this).val().length;
$('#' + countHeadline1).text(cs);
cs = $(this).val();
$('#' + headlineText1).text(cs);
}
c += 1;
Thank you,
EDIT: here is the code that create the element on click on a button:
jQuery('#add').on('click', function() {
c += 1;
jQuery('#parent').append('<hr><div>Headline 1:<br /><div><INPUT TYPE="text" placeholder="Headline" onkeydown="javascript:stripspaces(this)" id="headline1'+ c +'" maxlength="30" style="width: 350px;float:left;min-height: 32px;"><span id="countHeadline1'+ c +'" class="adCounter" style="color: rgb(255, 255, 255);float:left;position: inherit;margin-left: 0px;">0</span></div></div>');
});
An alternative is using Event Delegation for dynamically created elements.
Another approach is the feature data-attributes along with the function $data which stores useful information, in this case, the current id of the created element.
Additionally, this approach uses the CSS class inputs to identify the textfields and bind the event input to execute the function updateCount for any changes on those textfields.
function updateCount() {
var identifier = $(this).data('identifier'); //'data attribute' along with function 'data'.
$('#countHeadline1' + identifier).text($(this).val().length);
$('#headlineText1' + identifier).text($(this).val());
}
var c = 1;
$('#add').on('click', function() {
c += 1;
$('#parent').append('<br><br><br>Headline ' + c + ':<br /><INPUT TYPE="text" class="inputs" data-identifier="' + c + '" placeholder="Headline" id="headline1' + c + '" maxlength="30" style="width: 350px;float:left;min-height: 32px;"/><span id="countHeadline1' + c + '" class="adCounter" style="color: rgb(0, 0, 0);float:left;position: inherit;margin-left: 0px;">0</span><br><span id="headlineText1' + c + '" class="headLine" style="color: rgb(0, 0, 0);float:left;position: inherit;margin-left: 0px;">0</span>');
});
$('#parent').on('input', '.inputs', updateCount); // Event delegation
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='parent'>
Headline 1:
<br>
<INPUT class='inputs' TYPE="text" data-identifier='1' placeholder="Headline" id="headline11" maxlength="30" style="width: 350px;float:left;min-height: 32px;" />
<span id="countHeadline11" class="adCounter" style="color: rgb(0, 0, 0);float:left;position: inherit;margin-left: 0px;">
0
</span><br>
<span id="headlineText11" class="headLine" style="color: rgb(0, 0, 0);float:left;position: inherit;margin-left: 0px;">
0
</span>
</div><br>
<button id='add'>Add</button>
Important: I've removed this onkeydown="javascript:stripspaces(this)", so you need to decide where to call that function.
I understand using IDs seems like a direct way to target elements, but it might be more and more complicated as you keep adding content or elements to your app/page, so try to think of html as a structured set of elements that can have "patterns" or "templates", like this:
<div class="headline">
<input type="text">
<span class="headlineCount">0</span>
<span class="headlineText">Text</span>
</div>
With this in mind, lets check some important concepts of using JavaScript with HTML, that jQuery eases a lot
You can "traverse" HTML as a tree, with parents and children leafs (you might want to read this)
You can select elements using more than just IDs (you might want to read this).
Interacting with HTML inputs trigger events (you might want to read this)
Using html as the one stated above, you can have this:
<div class="headline">
<input type="text" value="One">
<span class="headlineCount">0</span>
<span class="headlineText">Headline One</span>
</div>
<div class="headline">
<input type="text" value="Two">
<span class="headlineCount">0</span>
<span class="headlineText">Two</span>
</div>
Two groups of class headline, each contains the input field, the count number and the text.
And with jQuery you can use code like this:
function update () {
var inputElement = this
$(inputElement).nextAll('.headlineCount').text(inputElement.value);
$(inputElement).nextAll('.headlineText').text(inputElement.value);
}
jQuery('.headline input').on('change', update)
Which basically reads like:
jQuery('.headline input').on('change', update)
For all input elements that are inside any element with class headline, attach a change event listener with update function.
function update () {
var inputElement = this
$(inputElement).nextAll('.headlineCount').text(inputElement.value);
$(inputElement).nextAll('.headlineText').text(inputElement.value);
}
The update function when triggered, will receive the <input> element as "context" (CHECK NOTE) and the this "variable" will refer to it.
Then with jQuery we do:
$(inputElement).nextAll('.headlineCount').text(inputElement.value);
Which means: starting from the input element find all elements with class headlineCount that are AFTER it, and change its text to the value of the input element.
I hope this small explanation is enough to get you started, indeed you're starting to handle some of the most important concepts of Front-End development, please don't stop refering to Mozilla documentation site (MDN) its wonderful.
NOTE: The this keyword is a somewhat advanced topic, to start I highly recommend to think of it as a "context" reference. But make sure to check it in MDN too!
Edit: now with Live demo: https://jsfiddle.net/3w7t1bhm/
Okay, after your edit, seeing that you have complete control over the HTML that's generated, I would definitely recommend going away from using IDs. Probably the easiest way would be to add classes to the headline and headlineText elements, and use them.
So, first, add classes to the elements that need them, when appending them in the click handler:
<INPUT TYPE="text" placeholder="Headline" onkeydown="javascript:stripspaces(this)" id="headline1'+ c +'" maxlength="30" style="width: 350px;float:left;min-height: 32px;" class="headline">
<span id="headlineText1'+ c +'" class=headline-text>
Then you can bind the change event on all elements with the headline class (You shouldn't need to bind to keyup and keydown as long as you've bound to change):
$(".headline").change(updateCount);
You can then update the count using jQuery's next method, and update the text using the parent and find methods:
function updateCount() {
var this$ = $(this);
var val = this$.val();
var cs = val.length;
this$.next().text(cs);
//Go up to the grandparent, which is the main div that wraps everything added in a single click, then search inside that for the element with the headline-text class
this$.parent().parent().find(".headline-text").text(val);
}
This makes some assumptions about the structure of the HTML that's being added, but if you need to change that structure, it would only take minor changes to this code to work with it.
I am using ASP.Net MVC along with Jquery to create a page which contains a contact details section which will allow the user to enter different contact details:
<div id='ContactDetails'>
<div class='ContactDetailsEntry'>
<select id="venue_ContactLink_ContactDatas[0]_Type" name="venue.ContactLink.ContactDatas[0].Type">
<option>Email</option>
<option>Phone</option>
<option>Fax</option>
</select>
<input id="venue_ContactLink_ContactDatas[0]_Data" name="venue.ContactLink.ContactDatas[0].Data" type="text" value="" />
</div>
</div>
<p>
<input type="submit" name="SubmitButton" value="AddContact" id='addContact' />
</p>
Pressing the button is supposed to add a templated version of the ContactDetailsEntry classed div to the page. However I also need to ensure that the index of each id is incremented.
I have managed to do this with the following function which is triggered on the click of the button:
function addContactDetails() {
var len = $('#ContactDetails').length;
var content = "<div class='ContactDetailsEntry'>";
content += "<select id='venue_ContactLink_ContactDatas[" + len + "]_Type' name='venue.ContactLink.ContactDatas[" + len + "].Type'><option>Email</option>";
content += "<option>Phone</option>";
content += "<option>Fax</option>";
content += "</select>";
content += "<input id='venue_ContactLink_ContactDatas[" + len + "]_Data' name='venue.ContactLink.ContactDatas[" + len + "].Data' type='text' value='' />";
content += "</div>";
$('#ContactDetails').append(content);
}
This works fine, however if I change the html, I need to change it in two places.
I have considered using clone() to do this but have three problems:
EDIT: I have found answers to questions as shown below:
(is a general problem which I cannot find an answer to) how do I create a selector for the ids which include angled brackets, since jquery uses these for a attribute selector.
EDIT: Answer use \ to escape the brackets i.e. $('#id\\[0\\]')
how do I change the ids within the tree.
EDIT: I have created a function as follows:
function updateAttributes(clone, count) {
var f = clone.find('*').andSelf();
f.each(function (i) {
var s = $(this).attr("id");
if (s != null && s != "") {
s = s.replace(/([^\[]+)\[0\]/, "$1[" + count + "]");
$(this).attr("id", s);
}
});
This appears to work when called with the cloned set and the count of existing versions of that set. It is not ideal as I need to perform the same for name and for attributes. I shall continue to work on this and add an answer when I have one. I'd appreciate any further comments on how I might improve this to be generic for all tags and attributes which asp.net MVC might create.
how do I clone from a template i.e. not from an active fieldset which has data already entered, or return fields to their default values on the cloned set.
You could just name the input field the same for all entries, make the select an input combo and give that a consistent name, so revising your code:
<div id='ContactDetails'>
<div class='ContactDetailsEntry'>
<select id="venue_ContactLink_ContactDatas_Type" name="venue_ContactLink_ContactDatas_Type"><option>Email</option>
<option>Phone</option>
<option>Fax</option>
</select>
<input id="venue_ContactLink_ContactDatas_Data" name="venue_ContactLink_ContactDatas_Data" type="text" value="" />
</div>
</div>
<p>
<input type="submit" name="SubmitButton" value="AddContact" id='addContact'/>
</p>
I'd probably use the Javascript to create the first entry on page ready and then there's only 1 place to revise the HTML.
When you submit, you get two arrays name "venue_ContactLink_ContactDatas_Type" and "venue_ContactLink_ContactDatas_Data" with matching indicies for the contact pairs, i.e.
venue_ContactLink_ContactDatas_Type[0], venue_ContactLink_ContactDatas_Data[0]
venue_ContactLink_ContactDatas_Type[1], venue_ContactLink_ContactDatas_Data[1]
...
venue_ContactLink_ContactDatas_Type[*n*], venue_ContactLink_ContactDatas_Data[*n*]
Hope that's clear.
So, I have a solution which works in my case, but would need some adjustment if other element types are included, or if other attributes are set by with an index included.
I'll answer my questions in turn:
To select an element which includes square brackets in it's attributes escape the square brackets using double back slashes as follows: var clone = $("#contactFields\[0\]").clone();
& 3. Changing the ids in the tree I have implemented with the following function, where clone is the variable clone (in 1) and count is the count of cloned statements.
function updateAttributes(clone, count) {
var attribute = ['id', 'for', 'name'];
var f = clone.find('*').andSelf();
f.each(function(i){
var tag = $(this);
$.each(attribute, function(i, val){
var s = tag.attr(val);
if (s!=null&& s!="")
{
s = s.replace(/([^\[]+)\[0\]/, "$1["+count+"]");
tag.attr(val, s);
}
});
if ($(this)[0].nodeName == 'SELECT')
{ $(this).val(0);}
else
{
$(this).val("");
}
});
}
This may not be the most efficient way or the best, but it does work in my cases I have used it in. The attributes array could be extended if required, and further elements would need to be included in the defaulting action at the end, e.g. for checkboxes.