Getting Index of Item in List coming from Array - javascript

I have this array:
var names = [
"Name1",
"Name2",
"Name3"
];
I converted this to Unorder List for HTML:
for(i = 0; i < names.Length; i++){
text += "<li>" + names[i] + "</li>";
}
text += "</ul>";
document.getElementById("choices").innerHTML = text;
Now, I got this:
Name1
Name2
Name3
And I am happy with the result. But now I want if someone click on Name2 so it alert me the index of the value. What I want is it should in Mobile App (Cordova) so that when user click on List Item it will show details on other activity (Some other page).
PS:
I checked:
var index = $( "li" ).index( this );
and
var index = $("ul li.active").index();
But seems like these are not made for me.
May be I should Dynamically assign ID's to each <li> item? What should I do now?

You can directly get index using index method.
$("li").click(function () {
alert($(this).index());
});
If you have multiple ul elements on page and you want to bind click event to some specific element you can do this.
To bind click on element by id
$("#YourUlId li").click(function () {
alert($(this).index());
});
To bind click event by class
$(".YourUlClass li").click(function () {
alert($(this).index());
});

$( "li" ).index will return elements index with respect to all li elements in DOM.
You need to use .index() with jquery object of clicked element. It will return the elements index in its parent container:
var index = $(this).index();

Pass the id dynamically in for loop
for(i = 0; i < names.Length; i++){
text += "<li id="+i+">" + names[i] + "</li>";
}
assign the click event, u will get the id by below code
$(li).click(function(){
alert($(this).attr("id"));
});

use this for getting the current element
<ul>
<li>Male</li>
<li>Female</li>
</ul>
<script>
$("li").click(function(){
alert($(this).index())
})
</script>

See below working snippet
var names = [
"Name1",
"Name2",
"Name3"
];
var text='<ul>';
for(i = 0; i < names.length; i++){
text += "<li>" + names[i] + "</li>";
}
text += "</ul>";
document.getElementById("choices").innerHTML = text;
$('li').on('click',function(){
alert($(this).index())
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="choices"></div>

Using native javascript, you can just create a function that will alert the index of the array value corresponding the li element value/id
First you attach the function on the choices
document.getElementById('Name2').setAttribute('onclick','checkIndex(this)');
then loop through the array and hunt for the matching array value
function checkIndex(item){
for(i=0;i<names.length;i++){
if(names[i] == item.innerHTML){ //or item.id
alert(names.indexOf(names[i]));
}
}
}

I would handle it in a declarative way, using html data-attributes, handled by jquery. see here
Here's an example.
var names = ["jack", "mary", "lou", "andrew"];
var text = "<ul>";
for (var i = 0; i < names.length; i++) {
text += "<li data-id='" + i + "'>" + names[i] + "</li>";
}
text += "</ul>";
document.getElementById("choices").innerHTML = text;
$("li").click(function(e){
alert($(this).data("id"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
My Choice
<div id="choices"></div>
</body>
</html>
Of course you can change data-id with whatever you want, or either add other attributes (data-page ? data-txt ? ) and handle all this in a proper way.
Also, dynamically assign ids to your list is a possibility, but I prefer this because I find it more flexible.

Related

Why doesn't my innerHTML method work to list things in my contact form?

I am making a program, and I'm wondering why all I see on my html page is the form, but only a single . where the bulleted list for an unordered list should be. I input the user input in the fields, but it doesn't show me the data in the fields, like it's supposed to, when I click submit. Here's the code.
function getFormElements() {
var gather_form_elements = new Array(
$("#first_name").val(),
$("#last_name").val(),
$("email").val(),
$("#phone_number").val()
);
displayValues(gather_form_elements);
}
function displayValues(gather_form_elements) {
for(i=0; i<gather_form_elements.length; i++)
{
document.getElementById("contact_info").innerHTML = "<li>" + gather_form_elements[i] + "</li>";
}
}
Because you are overiding it on every iteration. Try to accumulate the html before using innerHTML like this:
var html = "";
for(var i = 0; i < gather_form_elements.length; i++) {
html += "<li>" + gather_form_elements[i] + "</li>";
// ^^ the += is crucial. If you don't use it, it will just replace the content of html (the innerHTML in your code), we need to use += to append to html instead of overriding it.
}
document.getElementById("contact_info").innerHTML = html;
You can acheive the same result using only one line of code:
document.getElementById("contact_info").innerHTML =
'<li>' + gather_form_elements.join('</li><li>') + '</li>';

Removing elements by id using event Javascript dynamically

I have list of phones thats displaying as ul li. When user clicking button "buy" it creates new li with in another div "ordersDiv" user can delete his purchase from cart by clicking "Remove" And this must remove li with matching id.
Code that creates purchase:
$("#list").delegate("button",'click',function(){
var purchase = {id: null,name: null,price: null };
var purchases = [];
for(var i = 0; i < phones.length; i++){
if(this.id === phones[i].id){
purchase.id = phones[i].id;
purchase.name = phones[i].name;
purchase.price = phones[i].price;
//break;
purchases.push(purchase);
console.log(purchases);
$.each( purchases, function(i, purchase){
purchases.push("<li id='"+ purchase.id +"'>" + purchase.id +
"<br>" + purchase.name + "<br>" + "Price:" +purchase.price + "<br><button id='"+purchase.id+"' type='button' class='btn-default'>remove</button>" +"</li>" );
});
$('#ordersUl').append(purchases);
}
}
});
Code that supposed to remove li:
$("#ordersCartDiv #ordersUl").delegate("button","click", function() {
var buttonId = $(this).attr('id');
console.log(buttonId);
//$("li[id=buttonId]").remove();
$("#ordersUl").remove(buttonId);
console.log("test"); // code indentation
});
Problem is that this code doesn't removes anything.
you must pass a selector in remove function, like this:
$("#ordersUl").remove('#'+buttonId);
Use remove on button id.
$("# " + buttonId).remove();
No need to use ordersUl since id is unique(?).
If you don't have id unique:
$("#ordersUl #" + buttonId).remove(); // Will remove button inside #ordersUl
Remove the set of matched elements from the DOM.
Docs: http://api.jquery.com/remove/
$("#ordersUl").remove("#"+buttonId);
You should call remove function on element
$("li#"+buttonId).remove();
But ID is supposed to be unique, so it is bad idea to use it in this way. Use data- attributes or classes.

Finding element using its innerHTML

Please have a look to this DOM Tree...
<div>
<div>
<span> Home1 </span>
</div>
<span> Home2 </span>
<span> Home3 </span>
</div>
Now suppose I have a scenario where somehow I got the innerHTML of first span Home1.
Is it possible to get the element span and its parent div by using only this (Home1) information.
Here is what you want.
Here is html:
<label>opal fruits</label>
Here is jQuery:
$("label:contains(opal fruits)")
var mySpans = document.getElementsByTagName(span);
for(var i=0;i<mySpans.length;i++){
if(mySpans[i].innerHTML == 'Home1'){
var parent = mySpans[i].parentNode;
break;
}
}
this selects the parent of span having innerHTML Home1
There are so many ways to get info about your elements.
Using the innerHTML as an identifier is not a good solution.
You probably need some sort of event to that makes you search for that "Menu1"
So here is a click handler that works also on other events that give you information about what you have clicked.
function handler(e){
var txt='You clicked on a '+e.target.nodeName+'\n';
txt+='The innerHTML is '+e.target.innerHTML+'\n';
txt+='The text is '+e.target.textContent+'\n';
txt+='The parentNode is '+e.target.parentNode.nodeName+'\n';
alert(txt)
}
document.addEventListener('click',handler,false)
DEMO
function handler(e) {
var txt = 'You clicked on a ' + e.target.nodeName + '\n';
txt += 'The innerHTML is ' + e.target.innerHTML + '\n';
txt += 'The text is ' + e.target.textContent + '\n';
txt += 'The parentNode is ' + e.target.parentNode.nodeName + '\n';
alert(txt)
}
document.addEventListener('click', handler, false)
<div>
<div><span>Menu1</span></div><span>Menu2</span><span>Menu3</span>
</div>
If you want that your script searches for that "Menu1" you should consider adding that "Menu1" as an attribute on the span or parentNode.
<div id="Menu1">
<span>Home1</span>
</div>
and then call
document.getElementById('Menu1');
Which is very fast.
innerHTML method return String type. It don't associate with DOM tree.
You can use jQuery and it contains selector(fiddle):
$(":contains('Home1')").last()
var divRef; //Reference to the container of your div / span elements
var spans = divRef.getElementsByTagName("span");
var spanContainer;
for(var i = 0; i < spans.length; i++){
if(spans[i].innerHtml == "Home 1"){
spanContainer = spans[i].parentNode;
break;
}
}
if(spanContainer){
alert("Element has been found!");
}
function findNodeByInnerHTML(nodelist, innerHTML){
for(let ii = 0; ii < nodelist.length; ii++){
if(nodelist[ii].innerHTML === innerHTML)
return nodelist[ii]
}
}
let span = findNodeByInnerHTML(document.querySelectorAll('span'), 'home')

Jquery reading input field that was created from JSON loop

I cannot figure out for the life of me why this will not work. I am trying to pull the value of a textfield that was created with a loop from a json file.
In this code, at the very bottom I just do a simple click(function() {alert()} just to see if I can pull a value and its returning undefined. But if I remove '#name' and put in 'input' it captures it, but only for the first of several input fields.
Any help is really appreciated
JSON
{
"Controls": [{
"Button":[{ "Name":"Button", "x": "1","y": "2","width": "3","height": "4","Transition":"" }],
"Image":[{"x": "5","y": "6","width": "7","height": "8"}],
"TextField":[{"x": "9","y": "10","width": "11","height": "12","Rows":""}]
}]
}
The Code(there is soome getJSON stuff above this)
//Slide In Attributes Panel Based on Selected Object
$(document).on('click', '#code li', function () {
var index = $('#code li').index(this);
var selected = $(this).text();
switch (selected) {
case selected:
$('#options').hide();
hidePanels();
$('#temp').remove();
$('#objectAttributes').show("slide", 200);
break;
//If it does work show what variable is being used
default:
alert(selected);
break;
}
//Shows Selected LI Index
$('#codeIndex').text("That was div index #" + index);
//Pull list of Attributes for selected Object
$.getJSON('controls.json', function (data) {
//Build Attributes List
var attributeList = '<div id="temp">';
//Target based on selected object
var target = selected;
attributeList += '<div>' + target + '<div>';
$.each(data.Controls[0][target][0], function (kk, vv) {
attributeList += '<div style="float:right">' + kk + ':' + '<input type="text" id='+ kk + '>' + '</input>' + '</div>';
});
attributeList += '</div></div>';
attributeList += '</div>';
$('#objectAttributes').append(attributeList);
$('#temp').append('<div id="editIndex">'+"Modifying index" + " " +index+'</div>');
$(document).on('click', '#saveAttributes', function () {
var $x = $('#name').val();
alert($x);
})
});
});
Ok, so after a little hacking around with a jsfiddle the answer turned out to be a lot simpler than I first thought. Ever since HTML 4.01 class names and IDs have been case sensitive (reference), which means that your selector $('#name') wasn't matching the JSON Name.
So a simple change, such as in this simplified jsfiddle seems to work as desired. Hopefully this helps!

How to get the value of id of innerHTML?

I have created a html like this:
<body onload = callAlert();loaded()>
<ul id="thelist">
<div id = "lst"></div>
</ul>
</div>
</body>
The callAlert() is here:
function callAlert()
{
listRows = prompt("how many list row you want??");
var listText = "List Number";
for(var i = 0;i < listRows; i++)
{
if(i%2==0)
{
listText = listText +i+'<p style="background-color:#EEEEEE" id = "listNum' + i + '" onclick = itemclicked(id)>';
}
else
{
listText = listText + i+ '<p id = "listNum' + i + '" onclick = itemclicked(id)>';
}
listText = listText + i;
//document.getElementById("lst").innerHTML = listText+i+'5';
}
document.getElementById("lst").innerHTML = listText+i;
}
Inside callAlert(), I have created id runtime inside the <p> tag and at last of for loop, I have set the paragraph like this. document.getElementById("lst").innerHTML = listText+i;
Now I am confuse when listItem is clicked then how to access the value of the selected item.
I am using this:
function itemclicked(id)
{
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
But getting value as undefined.
Any help would be grateful.
try onclick = itemclicked(this.id) instead of onclick = 'itemclicked(id)'
Dude, you should really work on you CodingStyle. Also, write simple, clean code.
First, the html-code should simply look like this:
<body onload="callAlert();loaded();">
<ul id="thelist"></ul>
</body>
No div or anything like this. ul and ol shall be used in combination with li only.
Also, you should always close the html-tags in the right order. Otherwise, like in your examle, you have different nubers of opening and closing-tags. (the closing div in the 5th line of your html-example doesn't refer to a opening div-tag)...
And here comes the fixed code:
<script type="text/javascript">
function callAlert() {
var rows = prompt('Please type in the number of required rows');
var listCode = '';
for (var i = 0; i < rows; i++) {
var listID = 'list_' + i.toString();
if (i % 2 === 0) {
listCode += '<li style="background-color:#EEEEEE" id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
else {
listCode += '<li id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
}
document.getElementById('thelist').innerHTML = listCode;
}
function itemClicked(id) {
var pElement = document.getElementById(id).innerHTML;
alert("Clicked: " + id + '\nValue: ' + pElement);
}
</script>
You can watch a working sample in this fiddle.
The problems were:
You have to commit the id of the clicked item using this.id like #Varada already mentioned.
Before that, you have to build a working id, parsing numbers to strings using .toString()
You really did write kind of messy code. What was supposed to result wasn't a list, it was various div-containers wrapped inside a ul-tag. Oh my.
BTW: Never ever check if sth. is 0 using the ==-operator. Better always use the ===-operator. Read about the problem here
BTW++: I don't know what value you wanted to read in your itemClicked()-function. I didn't test if it would read the innerHTML but generally, you can only read information from where information was written to before. In this sample, value should be empty i guess..
Hope i didn't forget about anything. The Code works right now as you can see. If you've got any further questions, just ask.
Cheers!
You can pass only the var i and search the id after like this:
Your p constructor dymanic with passing only i
<p id = "listNum' + i + '" onclick = itemclicked(' + i + ')>
function
function itemclicked(id)
{
id='listNum'+i;
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
is what you want?
I am not sure but shouldn't the onclick function be wrapped with double quotes like so:
You have this
onclick = itemclicked(id)>'
And it should be this
onclick = "itemclicked(id)">'
You have to modify your itemclicked function to retrieve the "value" of your p element.
function itemclicked( id ) {
alert( "clicked at :" + id );
var el = document.getElementById( id );
// depending on the browser one of these will work
var pElement = el.contentText || el.innerText;
alert( "value of this is: " + pElement );
}
demo here

Categories

Resources