Convert Snippet of JS to JQuery - javascript

I want to convert the javascript code below to it's equivalent in JQuery.
Here's the snippet:
<script>
var str = '';
var elem = document.getElementById('formID').elements;
for(var i = 0; i < elem.length; i++)
{
str += "<b>Input Type:</b>" + elem[i].type + "&nbsp&nbsp";
str += "<b>Input Name:</b>" + elem[i].name + " ";
str += "<b>current Value:</b><i>" + elem[i].value + "</i> ";
str += "<br>";
}
document.getElementById('lblValues').innerHTML = str;
</script>
You can see I'm displaying what Inputs are within a Form element.
But I've reached my understanding of Loops and Elements of an Object. (especially form elements)
<script>
.........
// this much I know!
$("div#lblValues").html(str);
</script>

You can use $("#formID input") selector, this will return an array of inputs inside the form named 'formID'. Then, you can use each function to iterate over it. Hope this helps!
str = ""
$("#formID input").each(function(elem){
str += "<b>Input Type:</b>" + elem.type + "&nbsp&nbsp";
str += "<b>Input Name:</b>" + elem.name + " ";
str += "<b>current Value:</b><i>" + elem.value + "</i> ";
str += "<br>";
})

Related

Building html output with a input checkbox with javascript

I'm building a string that will be place in a div pro grammatically. I am trying to call the onclick attribute of the input checkbox and having a little bit of trouble. I am trying to pass a unique value id with each checkbox click. The code below is what I'm using. See below for the problem:
var count = 1;
$.each(JSON.parse(data.d), function (k, v) {
var searchName = v.searchName;
resultString += "<div class='row form-group'>";
resultString += "<div class='col-sm-1 right-content'><input type='checkbox' onclick = 'authorCheckboxclick(this)' id='" + searchName + "'></div>";
resultString += "<div class='col-sm-11'>";
resultString += "<span>";
//resultString += v.text
resultString += count + ". " + v.text
resultString += "</span>";
resultString += "<br />";
resultString += "<span>";
//resultString += "Consectetur adipisicing, Consequatur, 2015.";
resultString += "</span>";
resultString += "</div>";
resultString += "</div>";
//resultString += "<br><br>";
count++;
});
In the authorCheckboxclick function if I put var answerid = $(this).attr('id'); I get undefined.
function authorCheckboxclick(elem) {
var answerid = $(this).attr('id');
alert(answerid); //I get undefined
var answerid = $(this).attr(elem.id);
alert(answerid); //I get undefined
var answerid = $(this).attr(elem.id);
alert(answerid); //I get undefined
var searchTerm = elem.id;
alert(searchTerm); //I get proper value
searchTerm = searchTerm.substring(0, 3);
alert(searchTerm); //I get proper value
var answerid = $(this).attr(elem.id);
alert(answerid); //I get undefined
var search = searchTerm.toUpperCase();
var array = jQuery.grep(dataMembers, function (value) {
return value.toUpperCase().indexOf(search) >= 0;
});
Is there a reason my jQuery call is not working and my JavaScript is? Is there a best practice to send the id value to a junction? Am I mixing Apples with Orange? Which method show be faster?
The immediate solution to your problem is that you're using the this keyword in your function. As you are calling the function from an on* attribute the scope of the function will be the window, not the element that raised the event. To fix this, simply use the element you provide in the parameter, ie. $(elem) instead of $(this).
A better solution entirely would be to use an unobtrusive delegated event handler which can utilise the this keyword as you're attempting to. It also has the benefits of leaving cleaner HTML code and being a better separation of concerns. Try this:
var count = 1;
$.each(JSON.parse(data.d), function(k, v) {
var searchName = v.searchName;
resultString += '<div class="row form-group">' +
'<div class="col-sm-1 right-content"><input type="checkbox" id="' + searchName + '"></div>' +
'<div class="col-sm-11">' +
'<span>' + count + ". " + v.text + '</span><br />' +
'<span></span>' +
'</div>' +
'</div>';
count++;
});
$(document).on('change', '.row :checkbox', function() {
var answerid = this.id;
var search = searchTerm.toUpperCase();
var array = jQuery.grep(dataMembers, function(value) {
return value.toUpperCase().indexOf(search) >= 0;
});
});

How to use a js function inside $.getJSON?

how can I use my function JSONtoDate inside $.getJSON? This doesn´t work... val.timePosted return a string like 1448038589396, this work fine without the function but when I trying use the function to convert the str to date everything disappear
$(document).ready(function() {
function JSONtoDate(num){
var month = num.getMonth() + 1;
var day = num.getDate();
var year = num.getFullYear();
var date = day + "/" + month + "/" + year;
return(date);
}
  $.getJSON("http://www.freecodecamp.com/news/hot", function(json) {
var html = "";
var count = 0;
json.map(function(val) {
if(count == 0){
html += "<div class = 'row' >";
}
html += "<div class = 'stories col-md-3'>";
html += "<a href = " + val.link + " > <img src = " + val.image + " width = ' 200px'>";
html += "<p>" + val.headline + "</p> </a>";
html += "<p>" + val.rank + "</p>";
html += "<p>" + JSONtoDate(val.timePosted) + "</p>";
html += "</div>";
count += 1;
if(count == 4){
html += "</div>";
count = 0 ;
}
});
     $(".section").html(html);
});
});
Your function JSONtoDate expects a Date object as parameter, but you provide a String - "1448038589396". You can either pass a date, constructed from the Number value val.timePosted
html += "<p>" + JSONtoDate(new Date(parseInt(val.timePosted))) + "</p>";
^^^^^^^^^^^^^^^^^^ ^^
or let your function accept a string parameter:
function JSONtoDate (dateString) {
var date = new Date(parseInt(dateString));
var month = date.getMonth() + 1;
...
You have a JS error here:
1448038589396 is not a Date Object and it throws :
Uncaught TypeError: num.getMonth is not a function
try the following in jsFiddle
in JSONtoDate try the following
function JSONtoDate(num){
var num = new Date(num);
var month = num.getMonth() + 1;
var day = num.getDate();
var year = num.getFullYear();
var date = day + "/" + month + "/" + year;
return date;
}
http://jsfiddle.net/Lbt9jy8c/
I converted a string to UNIX timestamp based new Date() Object

How can create toggleable divs using javascript's innerhtml function?

I am trying to import information from an XML file, and create a name which, when clicked, will show more information. This information will be inside a div with no display until the header has been clicked.
This is the idea. Doesn't work.
$(document).ready(function () {
$.ajax({
type: "Get",
dataType: "xml",
url: 'service.xml',
success: function (xml) {
$(xml).find('Service[Name="j1979"]').find("Define").each(function () {
var PID = $(this).attr("PID");
var name = $(this).find("Name").text();
var source = $(this).find("source").text();
var doffset = $(this).find("DOffset").text();
var type = $(this).find("Type").text();
var length = $(this).find("Lenght").text();
var scale = $(this).find("Scale").text();
var noffset = $(this).find("NOffset").text();
var units = $(this).find("Units").text();
var moreinfo = "<div id='moreinfo'>source += '\r\n' += doffset += '\r\n' += type += '\r\n' += length += '\r\n' += scale += '\r\n' += noffset += '\r\n' += units</div>";
document.getElementById("j1979").innerHTML += PID += " ";
document.getElementById("j1979").innerHTML += < p onclick = "document.getElementById('moreinfo').style.display = 'inline-block'" > += "\r\n";
document.getElementById("j1979").innerHTML += moreinfo;
});
}
});
});
Sorry for any obvious mistakes and/or ugly code.
I assume that this is what you want to achieve: DEMO
just assume that the script in the demo is inside the success function
first, you have some error in here
document.getElementById("j1979").innerHTML += < p onclick = "document.getElementById('moreinfo').style.display = 'inline-block'" > += "\r\n";
this will not add the p element to the element with id j1979 because you write it like that, where you should be writing it like this
document.getElementById("j1979").innerHTML += "<p onclick=\"document.getElementById('moreinfo').style.display = 'inline-block';\" ></p>";
note the quotes at start and end, and the closing tag
second, there's no word or anything inside the p element that indicates that you could click it to show more information, so put the PID inside the p like this
document.getElementById("j1979").innerHTML += "<p onclick=\"document.getElementById('moreinfo').style.display = 'inline-block';\">" + PID + "</p>";
here's the full code with some CSS style to hide it before the user click on the PID
$(document).ready(function () {
var PID = "testPID";
var name = "Random Name";
var source = "Google";
var doffset = "1000";
var type = "A-9001";
var length = "50CM";
var scale = "100";
var noffset = "0";
var units = "Some Units";
var moreinfo = "<div id='moreinfo'>source: " + source + "</br>" + "doffset: " + doffset + "</br>" + "type: " + type + "</br>" + "length: " + length + "</br>" + "scale: " + scale + "</br>" + "noffset: " + noffset + "</br>" + "units: " + units + "</div>";
document.getElementById("j1979").innerHTML += "<p onclick=\"document.getElementById('moreinfo').style.display = 'inline-block';\">" + PID + "</p>";
document.getElementById("j1979").innerHTML += moreinfo;
});
#moreinfo {
display: none;
}
#j1979 {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div id="j1979"></div>
From the code you have, you can use '+' operator to concatenate strings.
When you need to use single quote inside string defined with single quote, you can use backslash (\) as escape character before it.
Also, you need to hide the div with class "moreinfo" initially.
As for new line, if you want each attribute in new line in moreinfo class, it can be achieved by using HTML "pre" tag or "br" tag or some other way.
So code would be:
var moreinfo = "<pre id='moreinfo' style='display:none'> source = " + source + "\r\n doffset = " + doffset + "\r\n type = " + type + "\r\n length = " + length + "\r\n scale = " + scale + "\r\n noffset = " + noffset + "\r\n units = " + units +"</pre>";
document.getElementById("j1979").innerHTML += '<p onclick="document.getElementById(\'moreinfo\').style.display = \'inline-block\'">\r\n' + PID + "</p>";
document.getElementById("j1979").innerHTML += moreinfo;
or
var moreinfo = "<div id='moreinfo' style='display:none'> source = " + source + "<br> doffset = " + doffset + "<br> type = " + type + "<br> length = " + length + "<br> scale = " + scale + "<br> noffset = " + noffset + "<br> units = " + units +"</div>";
document.getElementById("j1979").innerHTML += '<p onclick="document.getElementById(\'moreinfo\').style.display = \'inline-block\'">\r\n' + PID + "</p>";
document.getElementById("j1979").innerHTML += moreinfo;
If you want to toggle display on click, you can use ternary operator to give condition in onclick function:
var moreinfo = "<div id='moreinfo' style='display:none'> source = " + source + "<br> doffset = " + doffset + "<br> type = " + type + "<br> length = " + length + "<br> scale = " + scale + "<br> noffset = " + noffset + "<br> units = " + units +"</div>";
document.getElementById("j1979").innerHTML += '<p onclick="document.getElementById(\'moreinfo\').style.display == \'inline-block\' ? document.getElementById(\'moreinfo\').style.display = \'none\' : document.getElementById(\'moreinfo\').style.display = \'inline-block\'">\r\n' + PID + "</p>";
document.getElementById("j1979").innerHTML += moreinfo;
I wrote a program where I needed to toggle a div with javascript. I found a solution with this code.
function toggle( selector ) {
var nodes = document.querySelectorAll( selector ),
node,
styleProperty = function(a, b) {
return window.getComputedStyle ? window.getComputedStyle(a).getPropertyValue(b) : a.currentStyle[b];
};
[].forEach.call(nodes, function( a, b ) {
node = a;
node.style.display = styleProperty(node, 'display') === 'block' ? 'none' : 'block';
});
You can then call the function with:
toggle('.idOrClass');
make sure you use single quotes around the class or id name
Hope this helps! :)

Target Specific Javascript Object Literal fields and array with jquery

I cant seem to get this to work. Im trying to do two things
A). Get the following code to show up correctly. The first element is show 'undefined
<ul>
<li>Button
<ul>
<li>x:1</li>
<li>y:2</li>
<li>width:3</li>
<li>height:4</li>
</ul>
</ul>
Here is my code:
$(document).ready(function() {
var data = {
"Controls": [{
"Button":[{ "x": "1","y": "2","width": "3","height": "4" }],
"Image":[{"x": "5","y": "6","width": "7","height": "8"}],
"TextField":[{"x": "9","y": "10","width": "11","height": "12"}]
}]
}
var str = '<ul>';
$.each(data.Controls, function(k, v) {
str += '<li>' + k[0] + '</li><ul>';
for(var kk in v.Button[0]){
str += '<li>' + kk + ':' + v.Button[0][kk] + '</li>';
}
str += '</ul>';
});
str += '</ul>';
$('div').append(str);
})
And
B). trying to display a list(separate list from above) of just the fields. like this:
<li>Button</li>
<li>Image</li>
<li>TextField</li>
I think that the answer to the second lies in the first, but I cannot seem to get the targeting right.
Any help is appreciated
Demo
To get the first list:
var str = '<ul>';
var target = "Button";
str += '<li>' + target + '<ul>';
$.each(data.Controls[0][target][0], function(kk, vv){
str += '<li>' + kk + ':' + vv + '</li>';
});
str += '</ul></li>';
str += '</ul>';
To get the second list:
var str = '<ul>';
$.each(data.Controls[0], function(k,v) {
str += '<li>' + k + '</li>';
});
str += '</ul>';
To target them by index, so Button is 0:
var str = '<ul>';
var target = 0;
var count = 0;
$.each(data.Controls[0], function(k,v) {
if(count == target)
{
str += '<li>' + k + '<ul>';
$.each(v[0], function(kk, vv){
str += '<li>' + kk + ':' + vv + '</li>';
});
str += '</ul></li>';
return false; // <-- break because we got what we wanted
}
count++;
});
str += '</ul>';
First of all, this has nothing to do with JSON. JSON is a string-serialization format. What you have here is an object literal.
Second, I have no idea why you are wrapping all your object definitions inside Controls, with arrays, seems like a lot of extra hassle. You are also doing things in a very non-jQuery way.
You could try something like this:
var data = {
"Controls": {
"Button":{ "x": "1","y": "2","width": "3","height": "4" },
"Image":{"x": "5","y": "6","width": "7","height": "8"},
"TextField":{"x": "9","y": "10","width": "11","height": "12"}
}
}
$('div').append('<ul id="outer_ul">');
$.each(data.Controls, function(key, value) {
$('#outer_ul').append('<li>' + key + '</li>', '<ul id="' + key +'">');
$('#field_list').append('<li>' + key + '</li>');
$.each(value, function(key2, value2) {
$('#' + key).append('<li>' + key2 + ':' + value2 + '</li>');
}
}
This code populates both you div as well as a ul with the id of field_list which would represent the container into which you want to put the second list (so adjust this code according the the proper jQuery selector you want to use.

Add anchor point to headers?

I have a really big html-document consisting of a number of <h4> headers accompanied by a short <p> 'body'.
I need to add an anchor point (is it the correct term, btw?) to each of the headers.
I'm iterating over the headers, and adding them to a menu-ul:
headz = document.getElementsByTagName("h4");
arrayOfHeaders=[];
x = 0;
y = headz.length;
$("#menu").html("<ul>")
while (x<y){
arrayOfHeaders[x] = "<li><a href='#" + x +"'>" + headz[x].innerText + "</a></li>";
$("#menu").append(arrayOfHeaders[x])
x++;
}
$("#menu").append("</ul>")
I need a way to attach the anchor points to the headers.
Edit: To clarify - what i need is the add a name-tag to each of the -elements.
The first header should be edited from '<h4>' header'</h4>' to '<h4 name="0">'...
Without editing the html, of course.
Set ids to the if they do not have one.
headz = document.getElementsByTagName("h4");
arrayOfHeaders=[];
x = 0;
y = headz.length;
var str = "<ul>";
while (x<y){
var elem = headz[x];
var id = elem.id || "heading_" + x;
elem.id = id;
str += "<li><a href='#" + id +"'>" + elem.innerText + "</a></li>";
x++;
}
$("#menu").append( str + "</ul>");
and FYI innerText is not cross browser friendly.
jQuery solution
var str = "<ul>";
$("h4").each(
function(i){
var id = this.id || "header_" + i;
this.id=id;
str += '<li>' + this.innerHTML + '</li>';
}
);
str += "</ul>";
$("#menu").append(str);
Since you used jquery already, thought id write it all in it:
var html = '<ul>';
$('h4').each(function (index, header) {
html += '<li>' + header.html() + '</li>';
});
html += '</ul>';
$('#menu').append(html);
This might solve your problem
headz = document.getElementsByTagName("h4");
arrayOfHeaders=[];
x = 0;
y = headz.length;
var html = "<ul>";
while (x<y){
html += "<li><a href='#" + headz[x].id +"'>" + headz[x].innerText + "</a></li>";
x++;
}
$("#meny").append( html + "</ul>")
This one is similar to rissicay's answer but I think it's more concise:
var html = []; // create an empty array to store iterated html in
// loop over every heading...
$('h4').each(function(index) {
// and add it to array previously created
html.push("<li><a href='#" + index +"'>" + $(this).html() + "</a></li>");
// add name attribute to heading
$(this).attr('name', index);
});
// finally, append all to menu together with unordered list
$('#menu').append('<ul>' + html.join() + '</ul>');
Basically, try to minimize dom manipulation (.append(), .prepend(), .html()) as much as possible
I think the concept you refer to is sometimes known as an "internal link" - see here under the second section "HTML Links - The id Attribute".
Now looking at your example code you are clearly using jQuery so why not make the most of it?
$("h4").each(function() {
$("#links").append("<a href='#" + this.id + "'>link to " + this.id + "</a><br /><br />");
});
See the following fiddle - http://jsfiddle.net/r0k3t/PhrB6/
Hope that helps.

Categories

Resources