I'm creating a dynamic form with javascript which contains a drop down list and an input text as below :
$(document).ready(function() {
document.write("<FORM>");
document.write("<SELECT NAME='SelectMenu'>");
for (var i = 1; i <= 3; i++)
document.write("<OPTION>" +"one"+"</OPTION>");
document.write("<OPTION>" +"two"+"</OPTION>");
document.write("<OPTION>" +"three"+"</OPTION>");
document.write('</SELECT>');
document.write("<br>Entry <input type='text' name='myInputs[]'>");
document.write("<button onClick="ChoixDeQuestion()">Show</button>");
document.write('</FORM>');
});
The problem here is that I can't access those fields since they don't even exist in the source code of the page.
I want to get the entered text value and the selected item of the list.
So Any idea please!!
Thanks
Using document.write should be avoided. Its not a good practice.
You are using jQuery and its very easy to dynamically create elements in jQuery.
You can do something like this,
$(document).ready(function() {
var options = '';
for (var i = 1; i <= 3; i++)
options +='<option>one</option>';
options +='<option>two</option><option>three</option>';
var html = '<select>' + options + '</select><br>Entry <input type="text" name="myInputs[]" />';
var button = $('<button>Show</button>').click(function(e){
// Code to be executed when button is clicked
e.preventDefault(); // since by default button submits the form
alert('button is clicked');
});
$("<form></form>").append(html).append(button).appendTo('body');
});
jsFiddle
If you know a basic jQuery, everything is self explained, but do let me know if something bothers you :)
Instead of using the basic syntax "document.write(...)", you should use dynamic elements and creating new HTML elements.
Document.write only actually displays the text without really inserting it.
If you want to edit your HTML later on, you need the element to be created and added to the document.
Using, for example, the "CreateElement" syntax.
Here's a good tutorial to get you started on how to create a form dynamically.
Afterwards you can append elements to it, and create many more elements that way.
If you're already using jQuery, make more use of it:
$(document).ready(function() {
var form = $('<form />'),
dropdown = $('<select />', {
name: 'SelectMenu'
}),
textbox = $('<input />', {
type: 'text',
name: 'myInputs[]'
}),
button = $('<button />', {
text: 'Show'
}).on('click', ChoixDeQuestion);
for (var i = 1; i <= 3; i++) {
$('<option />', {
text: i
}).appendTo(dropdown);
}
form
.append(dropdown)
.append('<br />Entry')
.append(textbox)
.append(button)
.appendTo('body');
});
This is creating all the nodes and inserting them into the DOM in a nice way; you can also just create one big string contents with your html, and then do this:
$(contents).appendTo('body');
Related
Can anyone tell me how to hide the RESET button using DOM?
I am trying to make a uservent script with beforeLoad function that will hide/remove RESET button from a record.
I found a solution:
var form = ctx.form;
var field = form.addField({
id: 'custpage_code',
type: 'inlinehtml',
label: 'Code'
});
field.defaultValue = '<script>' +
'document.getElementById("resetter").style.display = "none";' +
'document.getElementById("tdbody_resetter").style.display = "none";' +// removed the extra line along the button
'</script>';
The other alternative is JQuery which is already pre-loaded in NS.
var hideFld = context.form.addField({
id:'custpage_hide_buttons',
label:'not shown - hidden',
type: serverWidget.FieldType.INLINEHTML
});
var scr = "";
scr += 'jQuery("#tbl_resetter").hide();';
scr += 'jQuery("#print").hide();';
hideFld.defaultValue = "<script>jQuery(function($){require([], function(){" + scr + ";})})</script>"
You can hide almost any element with this. Just search the page source for the element ID:
The "Reset" button's element is usually a table with the ID tbl_resetter. Add multiple elements easily as above.
I am creating a form dynamically and therefore edit the form elements’ properties. When attempting to change the label, assigning an auto-generated id works fine but when changing this label using the generated id, the function or keyup() from jQuery keeps calling all the previously created label id(s). this means when i want to edit one label, it ends up editing every label.
HTML
<input type="text" id="change-label"><br><br>
<button id="add-button">add label</button>
<div id="add-label"></div>
JavaScript/jQuery
$('#add-button').click(function(){
var div = document.createElement('div');
var textLabel = document.createElement('label');
var labelNode = document.createTextNode('untitled');
textLabel.appendChild(labelNode);
textLabel.id = autoIdClosure();
$('#change-label').val('untitled');
div.appendChild(textLabel);
$('#add-label').append(div);
});
var autoIdClosure = (function(){
var counter = 0;
var labelId = "textInputLabel";
return function(){
counter += 1;
var id = labelId + counter;
editLabelWrapper(id)
return id;
}
})();
function editLabelWrapper(id){
function editLabel(){
var value = $(this).val();
$("#"+id).text(value);
}
$("#change-label").keyup(editLabel).keyup();
}
I’ve already found an alternative using onkeyup="$('#'+globaID).text($(this).val());", but I need to understand what I was doing wrong so I can learn from it.
JSFiddle
I think you are overthinking the matter...
Instead of using an unique id, rather use classes, makes it easier to handle.
So change <div id="add-label"></div> to <div class="add-label"></div>
Then what you want to do is, when a value is given in #change-label you want it in the last div.add-label.
So the function will become this:
$("#change-label").on('keyup', function() {
$('.add-label:last').text( $(this).val() );
});
Next what you want to do is bind a function to #add-button. Once it gets clicked, we want to add a new div.add-label after the last one. And empty the #change-label. You can do that by using this function:
$('#add-button').on('click', function() {
$('.add-label:last').after('<div class="add-label"></div>');
$('#change-label').val('');
});
Updated Fiddle
I'm new to JQuery and I noticed this line $('#DivID [type=checkbox]') and I was wondering if I can also find the select or option tags using the same method.
Update: I have a div that has more than more tag, I'm trying to get the DropDownList/Select that it's value's just changed.
Update2 I'm using InstaFilta a JQuery plugin that filter the content based on a customized attribute appended to my content tags. Below is a snippet for the function that do the same when working with CheckBoxes, and I'm trying to edit it to work with DropDownLists/Select controls.
var $ex10Checkboxes = $('#ex10 [type=checkbox]');
$ex10Checkboxes.on('change', function() {
var checkedCategories = [];
$ex10Checkboxes.each(function() {
if ($(this).prop('checked')) {
checkedCategories.push($(this).val());
}
});
ex10.filterCategory(checkedCategories, true);
});
You would find the option tags as follows:
$("#DivID option")
Likewise the select tags:
$("#DivID select")
You can then iterate over the returned objects to inspect the individual elements:
var foo = $("#DivID option");
var i;
for (i = 0; i < foo.length; i += 1) {
console.log(foo[i].val()); //or whatever
}
To find the selected element you could check out this question:
$("#DivID option:selected")
I would suggest checking out the JQuery page on Selectors JQuery Selectors
I'm trying to write some javascript that will grab the inner text of li elements (1-16) and put them into hidden fields.
var myValue9 = document.getElementById("fileName9").value;
oForm.elements["fileName9"].value = myValue9;
<input name="fileName9" type="hidden" id="fileName9" />
<li id="wavName9"> Some Text </li>
How do I return the text in between the <li> and put into the hidden field?
Simple JavaScript:
document.getElementById("fileName9").value = document.getElementById("wavName9").innerText;
You could, in this case, also use innerHTML but that would also give you the HTML the element contains.
LI tags don't have a .value property. Using plain javascript, you could do it this way:
oForm.elements["fileName9"].value = document.getElementById("wavName9").innerHTML;
Or, to do all of them from 1 to 16, you could use this loop:
for (var i = 1; i <= 16; i++) {
oForm.elements["fileName" + i].value = document.getElementById("wavName" + i).innerHTML;
}
Or since you also tagged your post for jQuery, using jQuery you could do it like this:
$("#fileName9").val($("#wavName9").text());
Or, to do all of them from 1 to 16:
for (var i = 1; i <= 16; i++) {
$("#fileName" + i).val($("#wavName" + i).text());
}
Use jQuery to do it.
var myvar = $("#wavName9").html()
I think this will do in for all li's
$("li[id^=wavName]").each(function(){
var $this = $(this);
$this.closest("input[id^=fileName]").val($this.text())
});
Create your li's with id's following such a structure: listitem-n, where n is 1-16 and input fields following the same structure hiddeninputs-n (n = 1-16)
using jfriend00's code, add it in a loop that will traverse 16 times, incrementing a count variable that you will use to transfer the data from list items to hidden inputs
var count = 0;
for( i=0; i < 16; i++){
count ++;
$("form #hiddeninput-"+count).val($("#listitem-"+count).text());
}
Better validate the code, but there's the general idea.
You could also create the hidden fields in javascript from scratch, which would make the code abit more stable IMO as there's less chances of a hidden field missing in the form when the js is executed.
Using jQuery:
$('#fileName9').val($('#wavName9').text());
Note that you can change .text() to .html() to return the HTML structure rather than just the text.
You could automate this for multiple <li>'s like so:
$('li[id^="wavName"]').each(function () {
var number = this.id.replace('waveName', '');
$('#fileName' + number).val($(this).text());
});
This selects all <li>'s who's id starts with "wavName" and stores the text within the <li> tag in the hidden input who's id starts with "fileName" and ends with the same integer as the <li> tag.
I have written a script that will load a series of products into a div tag.
I now want to be able to filter those products using a series of checkboxes.
jquery makes a $post to an ASP page that returns an XML dataset. The first element of the data set contains a list of manufacturers in this format ara|dai|sid|alp etc. The second element contains the manufacturer names of the codes above.
I then use this script to build a list of checkboxes into a div tag.
var mc = new Array();
mc = $("manCodes",xml).text().split(",");
var manTitles = new Array();
manTitles = $("manTitles",xml).text().split(",");
for ( var i=0, len=mc.length; i<len; ++i ){
m += '<span><input type="checkbox" value="' + mc[i] + '" name="man[]" id="man_'+i+'" />' + manTitles[i] +'</span>'//mc[i];
}
manufacturers = '<div id="filter" class="man">FILTER<br />' + m + '</div>';
$(".formSelect").append(manufacturers);
This works a treat and then in the Document Ready section I have a code segment that looks for any click on a checkbox:
$(document).ready( function() {
$("input:checkbox").click(function() {
loadXML($("#sortOrder option:selected").val(),$("#limitBy option:selected").val(),$("#productGroup").val());
});
});
This is where my code falls over because any click on any checkbox is not working. Its almost like JQuery cannot see these checkboxes that it has created.
Can anybody please help how to resolve this problem please?
Cheers
Graham
You need event delegation, otherwise the event handler will not fire for dynamically inserted/removed elements. .live or .delegate are two options.
$("input:checkbox").live("click", function() {
// implementation
});
or better:
$("form").delegate("input:checkbox", "click", function() {
// implementation
});
use jQuery.live() to capture events from dynamically added elements.
Attach a handler to the event for all
elements which match the current
selector, now and in the future.
$("input:checkbox").live("click", function() {
loadXML($("#sortOrder option:selected").val(),$("#limitBy option:selected").val(),$("#productGroup").val());
});
Try:
$(document).ready( function() {
$("input:checkbox").live("click",function() {
loadXML($("#sortOrder option:selected").val(),$("#limitBy option:selected").val(),$("#productGroup").val());
});
});