HTML checkbox won't display correctly with javascript - javascript

Shouldn't this javascript just display an unchecked checkbox followed by the text "MyCheckBox"? Instead, it's just displaying "checked."
<html>
<head>
<script>
var data = false;
document.write('<input type="checkbox" ' + data ? "checked" : "" + '>MyCheckBox');
</script>
</head>
<body>
</body>
</html>

Here's the correction:
document.write('<input type="checkbox" ' + (data ? "checked" : "") + '>MyCheckBox');
You were missing the parentheses.
Also, don't put that inside <head>, like Teemu said, you can't render HTML there.

Just Do This.
var data=false,
a=document.createElement("input");
a.setAttribute("type","checkbox");
a.checked=data;
document.body.append(a);

Even when you can have the desired result with this line:
document.write("<input type='checkbox' " + (data ? "checked" : "") + ">MyCheckBox");
It is not the best way, you are writing to a stream and that is a risky business. Handling in the structured way, you can do it in this way:
`var data = false;
var check=document.createElement("input");
check.id="mycheckbox"
check.type="checkbox";
check.checked=data;
document.body.appendChild(check)`

Related

How to check ajax data.d is null in append?

I am trying to append some data in html table using jquery that is working fine but when the data is null or empty i have to append another div to that html table.
Am trying like this
$("#table").append(data.d[i].one!=""?
"<td id='divs'>
<input id="+ data.d[i].one +" type=" + "checkbox" + " class=" + "cbCheck" + ">
<label for="+ data.d[i].one +"></label>
</td>":"<div></div>");
but it is not working please help me how to fix this...
Never understand why somebody use this
$("#table").append(data.d[i].one!=""?
"<td id='divs'>
<input id="+ data.d[i].one +" type=" + "checkbox" + " class=" + "cbCheck" + ">
<label for="+ data.d[i].one +"></label>
</td>":"<div></div>");
Instead of this:
//class declaration
function YourTableCell(name, value) {
this.input = document.createElement('input');
this.input.value = value;
this.input.name = name;
this.label = document.createElement('label');
this.label.text = 'My Label';
this.container = document.createElement('td');
this.container.appendChild(this.input);
this.container.appendChild(this.label);
}
//application buisness logic
if(data.d[i].one != ''){
var cell = new YourTableCell(data.d[i].name, data.d[i].value);
$("#table").append(cell.container);
} else {
$("#table").append(document.createElement('div'));
}
Using this approach you can incapsulate table cell building inside of your class and make your code much more readable and reusable. Also, as I see now, you are trying to append td inside of something with id #table, and look like it is incorrect, because you should append td inside of tr.
Also, using this you can get references to all objects such as inputs and avoid of $('input, select, textarea') selectors.
You could use something like this,
var html = '<div></div>';
if(data.d[i].one) {
html = '<td id="divs"><input id="' + data.d[i].one + '" type="checkbox" class="cbCheck"><label for="' + data.d[i].one + '"></label></td>';
}
("#table").append(html);
You could use :
if( data.d ){
//Your code
}
That will check if data.d is NULL or empty string "".
If you want to check in every iteration use the index i :
if( data.d[i] ){
//Your code
}
Hope this helps.
Take a look to https://stackoverflow.com/a/5515349/4281779.

Unexpected token u in JSON at position 0 i'm trying to do a plugin

I have a problem(or problems) with my code, when I'm trying running the script in the developer kit trows the error
unexpected token u in JSON at position 0...
funciones.js
$(document).ready(function (){
$("#btn1").click(function(){
$.ajaxSetup({ cache: false });
var url = "productos.json";
var myData = JSON.parse(JSON.stringify(url.responseText || null, function(data){
for (var team in data) {
var html = []; //variable html
html = '<div class="item"><b>Nombre: </b>' + data[team].producto.nombre + '<br/>[\n]';
html += '<b>Precio: $</b>' +data[team].producto.precio + '<br/>';//precio
html += '<b>Marca: </b>' +data[team].producto.marca + '<br/>';
html += '<b>Presentación: </b>' + data[team].producto.presentacion + '<br/>';
html += '<b>Contenido: </b>' + data[team].producto.contenido + '<br/></div>';
$("#div1").append(html);
}
}));
});
});
function block(){
document.getElementById("btn1").disabled = true;
}
productos.json
[
{
"nombre":"Coca-Cola",
"precio":30,
"marca": "Cocacola",
"presentacion":"Familiar grande",
"contenido":"3Lt."
},
{
"nombre":"Coca-Cola",
"precio":25,
"marca": "Cocacola",
"presentacion":"Familiar",
"contenido":"2.5Lt."
},
{
"nombre":"Coca-Cola",
"precio":15,
"marca": "Cocacola",
"presentacion":"individual",
"contenido":"1Lt."
}
]
HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script src="funciones.js" language="javascript" type="text/javascript"></script>
<script type="text/javascript" src="productos.json"></script>
<meta charset="utf-8">
<title>jQuery Ajax</title>
<link rel="stylesheet" href="stilo.css">
</head>
<body>
<div>
<div>Prueba basica de archivos</div>
<div id="div1"></div>
<button id="btn1" onclick="block()" type="button">Team location</button>
</div>
</body>
</html>
What is the problem here?Thanks in advance
There are several problems in your code. I have modified your code into a plunkr here You should visit the working plnkr to find what was corrected however I will put some snippets here also.
The line below does not do anything.
var myData = JSON.parse(JSON.stringify(url.responseText || null, function(data){
The actual ajax call was missing so I added it
$.ajax({
url: url
}).done(function(myData){
//your code here
}
Then the loop
html = 'Nombre: ' + data[team].producto.nombre + '[\n]';
Here data is an array so it needs to be treated as an array. Further each array item itself is producto.
So this is corrected to
for (var i = 0; i < data.length ; i++) {
var producto = data[i];
var html = []; //variable html
html = '<div class="item"><b>Nombre: </b>' + producto.nombre + '<br/>[\n]';
html += '<b>Precio: $</b>' + producto.precio + '<br/>'; //precio
html += '<b>Marca: </b>' + producto.marca + '<br/>';
html += '<b>Presentación: </b>' + producto.presentacion + '<br/>';
html += '<b>Contenido: </b>' + producto.contenido + '<br/></div>';
$("#div1").append(html);
}
There are several issues:
url.responseText is undefined, and so the error complains on the first character of that, i.e. the u of undefined. Look at how you defined url and notice how that does no have responseText.
There is no Ajax call in your code. Use $.getJSON for this.
Do not use JSON.parse nor JSON.stringify: they only make things worse. jQuery will have done the conversion for you already.
If html is supposed to be a string, then don't initialise it as an array with [].
the onclick attribute references a function block that is not in the global scope.
Either add a click handler via code, or via the onclick attribute, but not both. So combine the code in one single click handler via one method.
The property producto does not exist in your JSON, so all the references to it will fail. Remove that property from your code, unless your JSON is different from what you have in the question
Other remarks:
You mix jQuery and non-jQuery syntax. When you have jQuery, use it. So not document.getElementById().
[\n] is a strange thing to output. I would remove that.
The loop for (var team in data) can be written with of instead of in, that way team will be the object, not the index, which makes the rest of your code simpler.
A button element doesn't need a type="button" attribute
Here is code that corrects all these issues:
HTML:
<div>
<div>Prueba basica de archivos</div>
<div id="div1"></div>
<button id="btn1">Team location</button>
</div>
JavaScript:
$(document).ready(function (){
$("#btn1").click(function(){
$(this).disabled = true;
$.ajaxSetup({ cache: false });
$.getJSON("productos.json").done(function(data) {
for (var team of data) {
$("#div1").append(
$('<div>').addClass('item').append([
$('<b>').text('Nombre'), team.nombre, $('<br>'),
$('<b>').text('Precio: $'), team.precio, $('<br>'),
$('<b>').text('Marca: '), team.marca, $('<br>'),
$('<b>').text('Presentación: '), team.presentacion, $('<br>'),
$('<b>').text('Contenido: '), team.contenido, $('<br/>')
])
);
}
});
});
});

Accessing Wikipedia API with JSONP

I've been trying for the last few days to make my code work, but I just can't find the problem.
I want to make communication with the Wikipedia server and get their JSON API so I can make a list of items corresponding to the input value of searchInput.
I've been looking into JSONP, finding in the end that I can add "&callback=?" to my API request and that it should work.
Now, even though I've added it, the communication still isn't happening.
I've noticed that the console on codepen.io returns "untitled" for a moment while initializing the code after processing the "#searchInput" input.
Perhaps the problem is in my for...in loop.
Do you have any idea what I should do?
The link to my code: http://codepen.io/nedsalk/pen/zqbqgW?editors=1010
(JQuery is already enabled in the "settings" menu)
If you prefer the .html edition of the code:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Object Oriented JavaScript </title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"> </script>
</head>
<body>
<h1> Wikipedia viewer </h1>
Go random!
<form>
<input type="text" name="searchInput" id="searchInput" placeholder="Search Wikipedia"
onkeydown = "if (event.keyCode == 13)
document.getElementById('submit-button').click()"/>
<input type="submit" id="submit-button"/>
</form>
<div id="list"></div>
<script>
$(document).ready(function() {
$("#submit-button").on("click",function (){
var input=$("#searchInput").val();
$.getJSON('https://en.wikipedia.org/w/api.php?action=query&generator=search&gsrsearch=' + encodeURIComponent(input) + '&prop=extracts&exlimit=10&exintro&exsentences=2&format=json&callback=?',
function(API){
$("#list").empty();
for (var id in API.query.pages)
{if(API.query.pages.hasOwnProperty(id){
$("#list").html('<a target="_blank" href="http://en.wikipedia.org/?curid=' + id + '">'
+'<div id="searchList">'
+ "<h2>" + id.title + "</h2>"
+ "<br>"
+ "<h3>" + id.extract + "</h3>"
+ "</div></a><br>")
}}
})
})
})
</script>
</body>
</html>
You have several issues in your code:
you should hook to the submit event of the form, not the click of the button, and use event.preventDefault() to stop the submission.
you loop through the keys of the returned object and attempt to access properties of those strings, instead of using the keys to access the underlying properties.
you set the html() in each loop, so only the final item will be visible. You should use append() instead.
Try this:
$("form").on("submit", function(e) {
e.preventDefault();
var input = $("#searchInput").val();
$.getJSON('https://en.wikipedia.org/w/api.php?action=query&generator=search&gsrsearch=' + encodeURIComponent(input) + '&prop=extracts&exlimit=10&exintro&exsentences=2&format=json&callback=?', function(response) {
var pages = response.query.pages;
$("#list").empty();
for (var id in pages) {
$("#list").append('<a target="_blank" href="http://en.wikipedia.org/?curid=' + id + '">' +
'<div id="searchList">' +
"<h2>" + pages[id].title + "</h2>" +
"<br>" +
"<h3>" + pages[id].extract + "</h3>" +
"</div></a><br>")
}
});
});
Working example

Serializing an iframe's content from head to toe with HTML special characters within Javascript

I'm using an iframe as an html editor and I load its content by setting iframe's src attribute. Afterwards, I turn on iframe's designMode so I can edit the loaded html content.
Once user is done, he'll press a save button and I'll try to retrieve the edited html content and sending it to the server. It's just that I need the full content of the iframe, including the <html> and <!doctype>. The problem I've faced is that when I retrieve the iframe's content, its embedded javascript code has encoded all < into <, even within Javascript code!
Here's how I wrote my code:
<!DOCTYPE html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<iframe src="about: blank"></iframe>
<button>Save to textarea</button>
<textarea></textarea>
<script>
$(document).ready(function() {
var $iframe = $("iframe");
var $iframeBody = $iframe.contents().find('body');
$iframeBody.html('<scr'+'ipt>var x = 1 < 2;</scr'+'ipt><>&');
$iframe.contents().prop('designMode','on');
$("button").click(function() {
var serializer = new XMLSerializer();
var html = serializer.serializeToString($iframe.contents()[0])
$("textarea").val(html);
});
});
</script>
</body>
</html>
Pressing the save button will output:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<script>var x = 1 < 2;</script><>&
</body>
</html>
As you can see the result is unusable because there's no way I can tell apart which < should be replaced with < (unless the text is parsed)!!
Does anyone have any idea how to retrieve the contents of an iframe completely without ruining it?
First of all - you don't need XMLSerializer. You try to serialize html like xml. I think you need a html. So it will be better to use $iframe.contents().get(0).documentElement.outerHTML. This will return whole html of iframe without doctype. For doctype you can use this function:
function getDoctypeString (doc) {
var doctypeNode = doc.doctype;
if (!doctypeNode) {
return '';
}
return "<!DOCTYPE "
+ doctypeNode.name
+ (doctypeNode.publicId ? ' PUBLIC "' + doctypeNode.publicId + '"' : '')
+ (!doctypeNode.publicId && doctypeNode.systemId ? ' SYSTEM' : '')
+ (doctypeNode.systemId ? ' "' + doctypeNode.systemId + '"' : '')
+ '>';
}
And all together:
<!DOCTYPE html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<iframe src="about: blank"></iframe><br>
<button>Save to textarea</button><br>
<textarea cols=55 rows=10></textarea>
<script>
$(function() {
function getDoctypeString(doc) {
var doctypeNode = doc.doctype;
if (!doctypeNode) {
return '';
}
return "<!DOCTYPE " + doctypeNode.name + (doctypeNode.publicId ? ' PUBLIC "' + doctypeNode.publicId + '"' : '') + (!doctypeNode.publicId && doctypeNode.systemId ? ' SYSTEM' : '') + (doctypeNode.systemId ? ' "' + doctypeNode.systemId + '"' : '') + '>';
}
var $iframe = $("iframe");
var $iframeBody = $iframe.contents().find('body');
var $textarea = $("textarea");
$iframeBody.html('<scr' + 'ipt>var x = 1 < 2;</scr' + 'ipt><>&');
$iframe.contents().prop('designMode', 'on');
$("button").click(function() {
var iframeDocument = $iframe.contents().get(0);
$textarea.val(getDoctypeString(iframeDocument) + iframeDocument.documentElement.outerHTML);
});
});
</script>
</body>
</html>
You can decode HTML code by doing this:
var text = '<p>name</p><p><span style="font-size:xx-small;">ajde</span></p><p><em>da</em></p>';
var decoded = $('<div/>').html(text).text();
alert(decoded);
You can get the html of the iframe without any character substitution by using:
document.getElementById('iframe').contentDocument.documentElement.outerHTML;
Here's a working JSBIN.
The reason you cannot find the doctype of the iframe might be because the iframe does not have a doctype.
According to W3C adding a doctype to an iframe is optional.
I took a look at the iframe in Firefox v33 and Chrome v39 and it did not have a doctype. Only the owner document had a doctype. Try it out in your browser with this JSBIN.
Also, doctypes are used for legacy reasons, and if you are worried about older browsers, you can just prepend a doctype tag to your html string:
var html = document.getElementById('iframe').contentDocument.documentElement.outerHTML;
html = '<!DOCTYPE html>' + html;
$("textarea").val(html);

Not able to append options to select

I am not sure why this works but not when I pass in numbers
<form id="form1" runat="server">
<div id="facebookPhotos-iFrameContent">
<div>
<p>Log in</p>
<p id="LoginButtonContainer"><input type="image" id="btnLogin" src="images/loginBtn.jpg" /></p>
<p><select id="facebookAlbumDropdown" /></p>
<div id="facebookPhotosContainer" />
</div>
</div>
</form>
AddDropdownItem("-Select something test-", "-1", "testDropdown");
function AddDropdownItem(sText, sValue, sDropdownID)
{
$("#" + sDropdownID).append("<option value=" + sValue + ">" + sText + "</option>");
}
that works
but this does not:
var id = 104388426283811;
AddDropdownItem("-Select something test-", id.toString(), "testDropdown");
What happens is the default option shows up but then when it tries to add the second option it bombs out with no errors that I can see in the firebug console and then in the end the list goes blank (no options) when my code is done running.
JavaScript will interpret integers as strings where needed, there is no need to use toString().
Try putting the value in single quotes, like this:
function AddDropdownItem(sText, sValue, sDropdownID)
{
$("#" + sDropdownID).append("<option value='" + sValue + "'>" + sText + "</option>");
}
You asked, "Why would that matter." The answer. It is a good practice and it prevents problems when your values start having spaces in them. I ALWAYS put attribute values in quotes.
Now, for your problem... I just tried it with the following code and it works like a charm!
<p><select name="MyTestDropdown" id="testDropdown"></select></p>
<script type="text/javascript">
$(document).ready(function () {
AddDropdownItem("-Select something test-", "-1", "testDropdown");
AddDropdownItem("something else", "1", "testDropdown");
AddDropdownItem("another thing", 2, "testDropdown");
var id = 104388426283811;
AddDropdownItem("test big value", id.toString(), "testDropdown");
AddDropdownItem("Profile Pictures", 100001379631246, "testDropdown");
AddDropdownItem("Test Test2", 104388426283811, "testDropdown");
});
function AddDropdownItem(sText, sValue, sDropdownID)
{
$("#" + sDropdownID).append("<option value='" + sValue + "'>" + sText + "</option>");
}
</script>
Your original code actually works, too. I don't think there was a problem with it. :) Maybe you have a problem elsewhere in your code?
Based on the comment thread in the original question, here's my sample page that incorporates your logic (along with wiring up a button to add options to the select):
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery Test</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script language="javascript">
$(document).ready(function() {
$("#btnClick").click(function(e) {
e.preventDefault();
var id = 104388426283811;
AddDropdownItem("-Select something test-", id.toString(), "testDropdown");
//AddDropdownItem("-Select something test-", "-1", "testDropdown");
});
});
function AddDropdownItem(sText, sValue, sDropdownID)
{
$("#" + sDropdownID).append("<option value='" + sValue + "'>" + sText + "</option>");
}
</script>
</head>
<body>
<input id='btnClick' type='submit' value='click'></input>
<p><select name="MyTestDropdown" id="testDropdown"></select></p>
</body>
</html>
I don't have the iframes that you mentioned, but I'm using an input submit element to add items in. I'm preventing the default behavior of a submit button by calling e.preventDefault();, which then prevents the post back. I'm then able to add items to the select element.
I hope this helps.

Categories

Resources