I want to create checkboxes dynamically. I am doing that, however I am failing with setting the name of the label. I tried setting the inner html to a value, though it didn't work. What is the correct way to do it ?
source:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
</head>
<body>
<div data-role="page" >
<fieldset data-role="controlgroup" id="exampleGroup">
</fieldset>
</div><!-- /page -->
</body>
<script>
var someId = "Something";
for (var i = 0; i < 5; i++) {
var checkBox = $('<input>', {
type: "checkbox",
class: "custom",
id: someId + i.toString()
});
var checkBoxLabel = $('<label>', {
for : someId + i.toString(),
});
checkBoxLabel.innerHTML = "Hello world!"; // didn't work
checkBox.appendTo("#exampleGroup");
checkBoxLabel.appendTo("#exampleGroup");
}
</script>
</html>
Using text() you can set the text inside label
try this:
checkBoxLabel.text("Hello world!");
Use text() or html() to set the contents of a DOM node. The difference between them is how they handle HTML tags.
checkBoxLabel.html('<foo>');
// <label><foo></label>
checkBoxLabel.text('<foo>');
// <label><foo></label>
You should prefer text() when you do not need HTML.
Try this
JSFIDDLE
var someId = "Something";
for (var i = 0; i < 5; i++) {
var checkBox = $('<input>', {
type: "checkbox",
class: "custom",
id: someId + i.toString()
});
var checkBoxLabel = $('<label>', {
for: someId + i.toString(),
});
checkBoxLabel.text(someId + i.toString());
checkBox.appendTo("#exampleGroup");
checkBoxLabel.appendTo("#exampleGroup");
}
Following is the area you want to look at
checkBoxLabel.text(someId + i.toString());
I used jquery text to change the label text
http://api.jquery.com/text/
Related
At the moment i need to remove an li element created by jQuery when it has been clicked.
(function() {
$(document).ready(function() {
$("#likeform").submit(function(event) {
var input = $(this).children("input[name='thing']")
var thing = $(input).val()
$("#likes").append("<li>" + thing + "</li>")
$(input).val("")
event.preventDefault()
})
})
var li = $('<li/>')
.onclick(function() {
$(this).remove()
})
}())
var listitems = document.getElementsByTagName("li")
for (var i = 0; i < listitems.length; i++) {
listitems[i].onclick = this.parentNode.removeChild((this))
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>My New Pen!</title>
<link rel="stylesheet" href="styles/index.processed.css">
</head>
<body>
<h1>What do you like?</h1>
<form id=likeform>
<input name=thing placeholder="a thing you like" size=30>
<input type=submit>
</form>
<ul id=likes></ul>
<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="scripts/index.js"></script>
</body>
</html>
Currently this has been successful apart from i need to manually reload the page for the change to take effect
Your problem is right here:
var li = $('<li/>').onclick(function() {
$(this).remove()
});
First of all you don't need the comparison operators (<, >) as JQuery will select elements by their tag names. Also, you can't add event listeners the "normal" way on dynamically created elements.
This is discussed right here.
To fix your problem replace the above with this:
$(document).on("click", "li", function() {
$(this).remove();
});
Working example:
(function() {
$(document).ready(function() {
$("#likeform").submit(function(event) {
var input = $(this).children("input[name='thing']")
var thing = $(input).val()
$("#likes").append("<li>" + thing + "</li>")
$(input).val("")
event.preventDefault()
})
})
var li = $(document).on("click", "li", function() {
$(this).remove();
});
}())
var listitems = document.getElementsByTagName("li")
for (var i = 0; i < listitems.length; i++) {
listitems[i].onclick = this.parentNode.removeChild((this))
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>What do you like?</h1>
<form id=likeform>
<input name=thing placeholder="a thing you like" size=30>
<input type=submit>
</form>
<ul id=likes></ul>
I think this is essentially what you are trying to do:
$('li').each(function (i) {
$(this).click(() => $(this).remove());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<ul>
<li>foo</li>
<li>bar</li>
</ul>
</body>
would you please try following.
(function() {
$(document).ready(function() {
$("#likeform").submit(function(event) {
var input = $(this).children("input[name='thing']")
var thing = $(input).val()
$("#likes").append("<li>" + thing + "</li>")
$(input).val("")
event.preventDefault()
})
})
}())
var listitems = document.getElementsByTagName("li")
for (var i = 0; i < listitems.length; i++) {
listitems[i].onclick = this.parentNode.removeChild((this))
}
$(document).on("click", "#likes li", function(){
$(this).remove();
});
i just want to know how to execute this [JSCODE][1] on page load, I'm a newbie and I cant figure it out. I just want to disregard the form or submit button and execute the script on page load. Thank You in advance!
[1]: http://jsfiddle.net/Noumenon72/9X3yZ/8/
Write your code inside anonymous function given below..
$(function() {
//Write your code here
})
Use jquery $(document).ready like this.
$(document).ready(function(){
//task which you want to perform
});
See you code below. I have mentioned where to call these functions.
$(document).ready(function(){
$('#domain').val('http://yourblog.blogspot.com/');
$('#get_tags').click();
});
function getTagsFromFeed(domain){
var myscript = document.createElement("script");
myscript.src = domain + "feeds/posts/summary?alt=json&max-results=0&callback=cat";
document.getElementsByTagName('head')[0].appendChild(myscript);
}
function cat(json){ //get categories of blog & sort them
var label = json.feed.category;
var lst=[];
for (i=0; i<label.length; i++){
lst[i] = label[i].term;
}
displayList(lst.sort()); //use any sort if you need that
}
function displayList(list) {
var mylist = document.getElementById("mylist");
mylist.innerHTML = "";
for (i=0; i<list.length; i++) {
var li = document.createElement("li");
li.appendChild(document.createTextNode(list[i]));
mylist.appendChild(li);
}
urlifyTagsInList(document.forms.myform.host.value);
}
function urlifyTagsInList(hostname){
var mylist = document.getElementById("mylist");
var newlist = document.createElement("ul");
var elements = mylist.getElementsByTagName("li");
for (j=0; j<elements.length; j++) {
var link = document.createElement("a");
var blah = document.createTextNode("blah");
link.href=hostname + "search/label/" + elements[j].innerHTML;
link.appendChild(elements[j].cloneNode(true));
newlist.appendChild(link);
}
mylist.parentNode.replaceChild(newlist, mylist);
newlist.id = "mylist";
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form id="myform" method="POST" onSubmit="getTagsFromFeed(document.forms.myform.host.value); return false;">
<p> Enter blogspot domain (http://yourblog.blogspot.com/):</p>
<input id="domain" type="text" name="host"></input>
<button id="get_tags" type="submit">Get tags</button>
</form>
<ul id="mylist">
</body>
</html>
If you want to use pure javascript, Document ready with pure JavaScript will help you.
A simple way to submit form onload is like this.
$(document).ready(function(){
$('#myForm').submit();
});
I don't know why this code doesn't work:
$("body").append("<select>");
for (j in boxes[i].ex_options ){
$("body").append("<option>"+boxes[i].ex_options[j]+"</option>");
}
$("body").append("</select>");
<select> items are not correctly displayed.
They're asking for this, just in case:
var Box = function (ex_solution, ex_img, ex_options) {
this.ex_solution = ex_solution;
this.ex_img = ex_img;
this.ex_options = ex_options;
}
var boxes = [];
boxes.push(new Box ("solution1","images/caja1>",["solution 1.1", "option 1.2", "option 1.3"]));
Thank you
append(), as #ArunPJohny points out, doesn’t concatenate strings; it appends DOM elements. When you add your first <select>, it creates a <select> element, then adds a bunch of <option>s outside of it. What you can do is create an element and pass an array of <option>s to append(), like this:
$("body").append(
$("<select>").append(
$.map(boxes[i].ex_options, function(option) {
return $("<option>").text(option);
})
)
);
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<link rel="stylesheet" type="text/css" href="http://brenda.upreach.org.uk/plugins/jquery.datepick.package-4.1.0/redmond.datepick.css">
<script type="text/javascript" src="http://brenda.upreach.org.uk/plugins/jquery.datepick.package-4.1.0/jquery.datepick.js"> </script>
<script type="text/javascript" language="javascript">
$(function() {
$('.datepick').datepick({
dateFormat: 'dd/mm/yyyy', showTrigger: '#calImg'});
});
$(document).ready(function(){
var Box = function (ex_solution, ex_img, ex_options) {
this.ex_solution = ex_solution;
this.ex_img = ex_img;
this.ex_options = ex_options;
}
var boxes = [];
boxes.push(new Box ("solution1","images/caja1>",["solution 1.1", "option 1.2", "option 1.3"]));
$("body").append("<select></select>");
$.each(boxes[0].ex_options, function(index, value){
console.debug(value);
$("body select").append("<option>"+value+"</option>");
});
});
</script>
<body></body>
I have been looking at the rally Object model, but I can't figure out how to grab the Name attribute of a Defect's Tag.
I made sure to include Tag and Tags in my fetch statement. I am storing all the defects into an array of objects called defectsNEWDEFECTS[]
I can return a Tag object by doing this:
tagNEWDEFECTS = defectsNEWDEFECTS[i].Tags;
document.write(tagNEWDEFECTS);
which will return this:
[object Object]
But, I can't seem to get it to return the NAME of the tag.
I tried:
tagNEWDEFECTS = defectsNEWDEFECTS[i].Tags.Name;
tagNEWDEFECTS = defectsNEWDEFECTS[i].Tags.Tag.Name;
tagNEWDEFECTS = defectsNEWDEFECTS[i].Tag.Name;
But they all return 'undefined'.
Any ideas how to get the name of a tag? Ultimately, the goal here is to have user-input custom tags that I can flag in my program to do certain things. For example, one tag will be named 'RollOverDefect'.
I need to be able to determine which Defects have a Tag called 'RollOverDefect'
Thanks!
Tags is a collection, so you'll ultimately need a nested loop over the Tags collection attribute to handle this. Once you've nested into an additional loop, you can reference the Tag Name via:
tagNEWDEFECTS = defectsNEWDEFECTS[i].Tags[j].Name;
Hope this is helpful - let us know if that gets the job done.
You may find this example to be useful:
<html>
<head>
<title>App Example: Defects with Tags</title>
<meta name="Name" content="App Example: Defects with Tags" />
<meta name="Version" content="2013.2" />
<meta name="Vendor" content="Rally Labs" />
<script type="text/javascript" src="/apps/1.33/sdk.js?apiVersion=1.43""></script>
<script type="text/javascript">
var table = null;
function defectsWithTagsExample() {
var rallyDataSource = new rally.sdk.data.RallyDataSource('__WORKSPACE_OID__',
'__PROJECT_OID__',
'__PROJECT_SCOPING_UP__',
'__PROJECT_SCOPING_DOWN__'
);
function itemQuery() {
var queryObject = {
key: 'defects',
type: 'Defect',
fetch: 'FormattedID,Name,State,Description,Tags,Name',
query: '(State = "Submitted")'
};
rallyDataSource.findAll(queryObject, populateTable);
}
function populateTable(results) {
if (table) {
table.destroy();
}
var tableDiv = document.getElementById('aDiv');
var config = {
'columnKeys' : ['FormattedID', 'Name', 'Description', 'State', 'Tags'],
'columnHeaders' : ['FormattedID', 'Name', 'Description', 'State', 'Tags'],
'columnWidths' : ['100px', '400px', '200px', '85px', '300px']
};
table = new rally.sdk.ui.Table(config);
table.addRows(results.defects);
for (i=0;i<results.defects.length;i++) {
myDefect = results.defects[i];
myTags = results.defects[i].Tags;
myTagString = "";
for (j=0;j<myTags.length;j++) {
myTag = myTags[j];
myTagName = myTags[j].Name;
if (j == 0) {
myTagString += myTagName;
} else {
myTagString += ", " + myTagName;
}
}
linkConfig = {item: {FormattedID: myDefect.FormattedID, "_ref" : myDefect._ref}};
defectLink = new rally.sdk.ui.basic.Link(linkConfig);
table.setCell(i, 0, defectLink.renderToHtml());
table.setCell(i, 4, myTagString);
}
table.display(tableDiv);
};
itemQuery();
}
rally.addOnLoad(defectsWithTagsExample);
</script>
</head>
<body>
<div id="aDiv"></div>
</body>
</html>
I have function that opens up a window, and the values from the newly opened window are listed in the opener window.
The 2nd window - has this function:
function AddOtherRefDoc(name, number) {
var remove = "<a href='javascript:void(0);' onclick='removeRefDoctor(this)'>Remove</a>";
var html = "<li><b> Referral Doctor: </b>"+name+"<b>, Referral No: </b>"+number+ " " +remove+" <input type='text' name='ref_docs' value='"+name+"'></input><input type='text' name='ref_nos' value='"+number+"'></input></li>";
opener.jQuery("#r_docs").append(jQuery(html));
}
The function that calls the one above is:
function addRefDoc(){
var count = 0;
var ref_docarray ;
var ref_noarray ;
<%for(int i1=0; i1<vec.size(); i1++) {
prop = (Properties) vec.get(i1);
String ref_no = prop.getProperty("referral_no","");
String ref_name = (prop.getProperty("last_name", "")+ ","+ prop.getProperty("first_name", ""));
%>
if(document.getElementById("refcheckbox_<%=ref_no%>").checked) {
count++;
if ((ref_doctor!=null)&&(ref_doctor!="")&&(ref_docno!=null)&&(ref_docno!="")) {
ref_docarray = ref_doctor.split(";");
ref_noarray = ref_docno.split(";");
if ((containsElem(ref_docarray,"<%=ref_name%>"))||(containsElem(ref_noarray,<%=ref_no%>))) {
alert("Referral doctor " + "<%=ref_name%>" + " already exists");
} else {
AddOtherRefDoc("<%=ref_name%>", <%=ref_no%>);
}
} else {
AddOtherRefDoc("<%=ref_name%>", <%=ref_no%>);
}
}
<%} %>
self.close();
}
function containsElem(array1,elem) {
for (var i=0;i<array1.length;i++) {
if(array1[i]==elem){
return true;
} else{
return false;
}
}
}
When this function is called, it is supposed to carry the 2 input elements "ref_docs" and "ref_nos" into the page that opened this window. But it is not doing so. It lists the elements alright but when I try to use "ref_docs" and "ref_nos" in another Javascript function in the 1st window, I see that "ref_nos" and "ref_docs" are empty.
What am I doing wrong?
function updateRd(){
var ref_docs = jQuery("#updatedelete").find('input[name="ref_docs"]');
var ref_nos = jQuery("#updatedelete").find('input[name="ref_nos"]'); alert(ref_docs.val() + ref_nos.val());
var rdocs = new Array();
var rnos = new Array();
ref_docs.each(function() { rdocs.push($(this).val()); } );
ref_nos.each(function() { rnos.push($(this).val()); } );
$('#r_doctor').val(rdocs.join(";"));
$('#r_doctor_ohip').val(rnos.join(";")); }
–
This function returns an error saying "ref_docs" and "ref_nos" are undefined.
I think it is trying to use the jQuery on the other page to find "#r_docs" on the current page.
Try:
jQuery(opener.document).find("#r_docs").append(html);
UPDATE:
I created index.html:
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.js"></script>
<script type="text/javascript">
window.jQuery = jQuery;
function openChild ()
{
var mychildwin = window.open("child.html");
}
</script>
</head>
<body>
<input type="button" value="click" onclick="openChild();" />
<div id="r_docs">
Redocs here.
</div>
</body>
</html>
and child.html:
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.js"></script>
<script type="text/javascript">
function AddOtherRefDoc(name, number) {
var remove = "<a href='javascript:void(0);' onclick='removeRefDoctor(this)'>Remove</a>";
var html = "<li><b> Referral Doctor: </b>"+name+"<b>, Referral No: </b>"+number+ " " +remove+" <input type='text' name='ref_docs' value='"+name+"'></input><input type='text' name='ref_nos' value='"+number+"'></input></li>";
jQuery(opener.document).find("#r_docs").append(html);
}
</script>
</head>
<body>
<input type="button" value="click" onclick="AddOtherRefDoc('name', 42);"/>
</body>
</html>
UPDATE2:
in your update function document.updatedelete has no attributes ref_docs and ref_nos.
try:
jQuery("#updatedelete")
.find('input[name="ref_docs"], input[name="ref_nos"]')
Where your form is
<form id="updatedelete" ... >
Your function that accesses the DOM elements is incorrect. updatedelete is not a property of document, nor will accessing a ref_docs or ref_nos property automatically build a collection of input elements. Since you're using jQuery already, try this:
var ref_docs = $('input[name="ref_docs"]');
var ref_nos = $('input[name="ref_nos"]');
That will give you Array (or at least array-like) objects that will let you access your inputs:
var rdocs = new Array();
var rnos = new Array();
ref_docs.each(function() { rdocs.push($(this).val()); } );
ref_nos.each(function() { rnos.push($(this).val()); } );
$('#r_doctor').val(rdocs.join(";"));
$('#r_doctor_ohip').val(rnos.join(";"));