html select execute javascript onload - javascript

I am using HTML select onchange event to fire another javascript function func1.
This html select is written into a form element, which are dynamically generated when users click on a button.
The problem is how can I fire the javascript func1 when the dynamically generated form is first shown ?
I am thinking of something along the line of on_first_show event for form ?
Here is the snippet. I couldnt get the alert('don') to work either (the one just after div)
var sPopupContents = "<div ><script type='text/javascript'>alert('don');</script> </div>"; // this javascript is not executed ? I cant get the alert.
sPopupContents += "<form name='theform' >";
sPopupContents += "<select name='theselect' onchange='alert(2);";
sPopupContents += "func1()>'";
sPopupContents += "<option value='0' selected='selected'>Value1</option><option value='1'>Value2</option><br/>";
sPopupContents += "</form>";
-- EDIT --
I guess I can add another option in the html select that tells users to select, so forcing the onchange to take effect. Or I can just add a Submit button.

You could use document.createElement method instead of using literal srings, and add the onchange event handler by calling addEventListener.
You are closing the select tag before the single quote
sPopupContents += "<select name='theselect' onchange='alert(2);";
sPopupContents += "func1()>'";
should be:
sPopupContents += "<select name='theselect' onchange='alert(2);";
sPopupContents += "func1()'>";

A library such as jQuery would let you do this:
(function() {
function selectChange() {
// save baby seals here
};
$('select[name=theselect]').live('change', selectChange)
$(document).ready(selectChange);
}();
You don't need a library for this for most browsers, however. A change event will bubble up to the containing element, so you can listen for it there. I believe it's IE that won't bubble up a change event.

Related

Javascript Escape Character Replacement

I'm using a button to dynamically generate a new table row in my form and the lines include calling functions with parameters. I tried using JQuery on the added lines to trigger the .blur() event, as was successfully done with the hardcoded first table row, but the page completely ignored it. So I'm trying another route of triggering the onblur() event from within the row HTML. I'm getting stuck on the function parameter, as I'm either messing up the escape character order or messing up the translation. I've already spent a few hours on this and tried doing research on Stack Overflow, so I'm hoping a second set of eyes would be able to help.
Here are the relevant pieces of code. The stored html is appended to my table row, which already works.
var strVar = 'myString';
var rowCount = $("#tbodyID td").closest("tr").length;
var rowNum = rowCount + 1;
var line17 = "<td><input type='number' class='form-control' name='named_qty' onblur='function(" + strVar + ")' id='row_R" + rowNum.toString() + "' /></td> ";
There are approximately 25 lines with varying html to be inserted. I was able to get it to work previously, but realized that a value was hardcoded and I needed it to be dynamic. The function it calls is accepting a string.
When inserted into the HTML document, this line should generally read:
<td><input type="number" class="form-control" name="named_qty" onblur="function('myString')" id="row_R2" /></td>
I did some more research and realized that I was using the JQuery blur() method as :
$('#id').blur( function() { }); and trying to call those functions, not realizing that the method only works for HTML elements that had been written to the DOM on page load.
Apparently the solution is to use the JQuery on() method as follows:
$(document).on("blur", '#id', function() { <insert code> });
From W3Schools,
Note: Event handlers attached using the on() method will work for both current and FUTURE elements (like a new element created by a script).
This removes the necessity to include the event function call in the HTML line to be appended to the DOM.

Strange design error when sending "select" from javascript

I have two sets of code, that basically sends a drop down list to a div from Javascript.
The strange thing is that I am basically sending the same thing in both the cases. But in the first code, the select drop down is perfectly being shown, while in the second code, it is being broken.
Code 1:
document.getElementById('start_day_div').innerHTML += "<select name='start_day' id='start_day'><option value='1'>option1</option><option value='2'>option2</option></select>";
Code 2: (Basically I am sending the same data as the code 1)
document.getElementById('start_day_div').innerHTML += "<select name='start_day' id='start_day'>";
document.getElementById('start_day_div').innerHTML += "<option value='1'>option1</option>";
document.getElementById('start_day_div').innerHTML += "<option value='2'>option2</option>";
document.getElementById('start_day_div').innerHTML += "</select>";
Any idea why this is happening for the same code?
After each call to element.innerHTML += the browser will correct any incorrect html.
In your case you create the following html (which is invalid in itself as <option>'s cannot float around like that.)
<select name='start_day' id='start_day'></select>
<option value='1'>option1</option>
<option value='2'>option2</option>
If you want to do it, you need to do it in one go. If you want to format it better, concatenate with a +:
document.getElementById('start_day_div').innerHTML += "<select name='start_day' id='start_day'>"
+ "<option value='1'>option1</option>"
+ "<option value='2'>option2</option>"
+ "</select>";
<div id="start_day_div"></div>
If you are creating an incomplete select, most browsers will correct the error by closing the select html in order to render the control and make it an accessible object in the DOM with the normal select object properties etc. So afterwards the options are appended separately. If you inspect the resulting html this backs this theory up.

Selected option not displaying as selected after append()

I'm building a string of HTML based on JSON data. In the HTML is a <select> with its <option>s. If the <option>'s value is the same as some JSON data, it includes the selected="selected" attribute to the option tag as well. After that, the whole shebang is .append()ed to a display.
All of that seems to work fine and dandy, except that the selected option isn't selected. Checking the code in Chrome's Web Dev tools shows that the selected="selected" attribute is there. Doing a console.log() of the :selected options picks them up. However, when I drill down to a specific <option> and look at it, is shows the selected attribute as set to false.
Wha...?
I've tried using the .select() and .attr("selected","selected") jQuery methods after-the-fact to force the issue, but neither has made any difference.
Can anyone else figure out what's going on here? It might just be my squirrely ignorance, but this seems to me like it should be working.
Code for reference. dataArray is an array of objects. $display is the jQuery wrapped <table> the HTML is .append()ing to:
$orderNumberField = jQuery("#orderNumber");
_orderNumberArray = $.parseJSON( $orderNumberField.val() );
for( n in dataArray ) {
var _displayString = "";
// ... other table data cells ...
_displayString += "<td><select class='orderNumSelect'>";
_displayString += " <option value=''></option>";
for( i in _orderNumberArray ){
_displayString += "<option value='" + _orderNumberArray[i] + "'";
if( dataArray[n].orderNum == _orderNumberArray[i] ) _displayString += " selected='selected'";
_displayString += ">" + _orderNumberArray[i] + "</option>";
}
_displayString += "</select></td>";
// ... still other table data cells ...
$display.append( _displayString );
}
I'm not sure what's not working on your code,but you can try to generate the elements rather than appending text. I tested out with this code and it works fine
<script>
var dataArray=["test","testm2","Tasat3"];
function append(){
var td=document.createElement("td");
var sel=document.createElement("select");
var o=document.createElement("option");
sel.appendChild(o);
for (n in dataArray){
o=document.createElement("option");
o.value=dataArray[n];
o.text=dataArray[n];
if (n==1) o.selected=true;
sel.appendChild(o);
}
td.appendChild(sel);
document.getElementById("display").appendChild(td);
}
append();
</script>
As it turns out, the code outlined above was not at fault for the behavior I described. There is other code executing after it that resets form inputs. The jQuery selector in the other code was written too generally and was picking up the generated select fields also when it shouldn't have.
Thank you to all the commentors. I did end up rewriting the code to use DOM elements instead of generating a string, which is a little easier to read. Hooray for unintentional side effects.

jquery selector checkboxes

My page is moderately complicated and I'm fairly sure its the jquery acting weird. So i'll add the relevant content first and if anyone needs more info let me know and I'll provide it.
The premise is that there is a div which holds keyword bubbles. These bubbles have a tooltip (qTip plugin) with relevant info that you can select and deselect. Sometimes keywords have overlapping relevant info so when one is deselected all others need to be deselected at the same time. This list of bubbles is built dynamically via ajax and can continue to be added on to the page live.
The problem is that some of the check boxes don't uncheck when I click on them, but if I click on the same one in another tooltip it works... which also now lets the original one work just fine. I have no idea why some work and others dont. I figure it has to do with the way the live onlick function binding and/or selectors are written.
The following function writes the html content of the tooltip based on a json object, so just assume the content is there. The jquery code at the bottom is the function I have bound to the checkboxes.
function constructSpecializationsHTML(data){
var html = '';
for(i = 0; i < data.specializations.length; i++){
if(data.specializations[i].name != ''){
html += "<span class='is-specialization-line'>";
html += "<input class='is-specialization-checkbox' type='checkbox' name='" + data.specializations[i].name + "' checked='" + isSpecializationChecked(data.specializations[i].name) + "'/>";
html += "<span>" + data.specializations[i].name + "</span>";
html += "</span><br />";
} else {
html += "This keyword is not known in our ontology";
}
}
return html;
}
$(document).on("click", ".is-specialization-checkbox", function(){
var $checkboxs = $(".is-specialization-checkbox[name='" + $(this).attr("name") + "']")
$checkboxs.prop("checked", !$checkboxs.prop("checked"));
});
Firstly, when the click event fires the "checked" property has already been changed, meaning that the states of your checkboxes are different.
Changing
!$checkboxs.prop("checked")
To
$(this).prop("checked")
Solves that.
Secondly when you have only displayed one tooltip your select is only returning one checkbox. If you display all the tooltips before checking or unchecking it returns the correct number. My guess is that qTip isn't adding the html for the tooltip to the DOM until it is displayed.
That's why not all your similarly named checkboxes are unchecking though (At least I think that's it!)
$(document).on("click", ".is-specialization-checkbox", function(){
var $checkboxs = $(".is-specialization-checkbox[name='" + $(this).attr("name") + "']")
$checkboxs.not($(this)).prop("checked", false);
});
changed this to $(this) - that way it is the specific checkbox that was clicked that is getting excluded from the deselection.

Button in list from Javascript loop throws back the of the list

I got this javascript loop which generates a unordered list with maybe 50 list items.. Now I want to put a button in every list item which stores the content in a database. Think retweet.
I figured out a way which is put the button and the content from the listitem within a hidden input in the loop but that seems like a bad shortcut. Like this:
html += "<form action=\"add.php\" method=\"post\"><input type=\"hidden\" value=\"" + listitem + "\" name=\"item\"\/>";
html += "<input type=\"submit\" value=\"repost\" \/><\/form>";
Using jQuery seems much more subtle and more like the right thing to do. I've gotten this far:
$("button").click(function()
var value = ($(this).text());
$.post('add.php',{value:value};
});
With a button in the loop instead of the input. But I can't even get the jQuery to response to the button click. Is there anyway this is possible or should I just go with the shortcut?!
The loop =
var html = "<li><h2 class=\"postTitle\">" + title + " <\/h2>";
html += "<p id=\"postText\" class=\"postText\">" + text + "</p></li>";
$('#Content').append($(html));
And the html where the loop ends up:
<ul id="list">
<div id="Content">
</div>
</ul>
From the code above the jQuery selector being used ("button") will not match anything in your code as you've used an input for the button; try:
$("input[type=submit]").click(function () {
...
});
Ideally use a more targeted selector as I presume you don't want every submit button to do this :)
Try giving your button a unique id?
resulting in:
$('#myId').click(function(){
//your code here
});
That is much better to specify.
You can also try to give it a class and an id
$('.myClass').click(function(){
var myButton = $(this).attr('id');
if(myButton == 'myId'){ do this} else if(myButton == 'myOtherId'){do this}
});
that way you can handle several buttons in one function, and if there are many buttons if statements will make your code look all messed up and you can use a select case :)
First, if you send your data via AJAX $.post, you should prevent submitting a form:
$("button[type=submit]").click(function(oEvent) {
oEvent.preventDefault();
// or in the end of handler
return false;
});
Second, <input> and <button> elements will return nothing in $(elem).text(), to get a value you should use $(elem).val() method.
Third, use the id attribute for HTML elements, this will help you manage DOM easier.

Categories

Resources