Unable to retrieve element through jquery - javascript

html file:
<div id ="main">
</div>
Javascript:
//create a div
var divElem = $('<div class="divText"></div>');
//create input element inside it
var inhtml = "<input type='text' id='12345' />";
//add to page
$(divElem).html(inhtml).appendTo('#main')
Following does not work as it is unable to find input element:
//retrieve input element
$('#12345').val('hello')
Following works:
document.getElementById('12345').value = 'hello'
Following works:
var ipElem = $(inhtml);
$(divElem).append(ipElem).appendTo('#main')
$(ipElem).val('hello')
Can anyone tell why first version of retrieving element does not work in jquery? (just starting with jquery... :) )
Edit:
I think '12345' works but not some weird id like: mytext0.15942923246580176
See here:
http://jsfiddle.net/9PVNb/4/

You're wrapping divElem in jQuery object twice:
var divElem = $('<div class="divText"></div>');
var inhtml = "<input type='text' id='12345' />";
$(divElem).html(inhtml).appendTo('#main') // Nop '$(divElem)' plus missing `;`
divElem.append(inhtml).appendTo('#main'); // Yup
EDIT:
Edit: I think '12345' works but not some weird id like: mytext0.15942923246580176
Your code at http://jsfiddle.net/9PVNb/4/ isn't working because:
// Your `id` has a `.` which you didn't escape
var elemid = 'mytext0.15942923246580176';
You can make it work by doing this:
alert($('#' + elemid).val()); //undefined. DOES NOT WORK
alert($('#' + elemid.replace('.', '\\.')).val()); // hello world IT WORKS!

works here: http://jsfiddle.net/xvKcd/
basic check:
are you using $(document).ready()? your code may be firing up before the element you needed was loaded.
did you load jQuery before anything else?
typos?

Related

How to find an element in HTML string and change an attribute using jQuery

This seems to be a very simple question but I've been at it for a couple of hours trying to make it work.
I have a string like:
var myhtml = '<div id="wrapper"><div id="full" width="800px"></div></div>';
I need to find my div #full, remove it's "*width*" attribute and then use myhtml with the updated version.
I'm using this in jQuery:
var newhtml = $(myhtml).filter("#full").removeAttr("width");
console.log(newhtml );
Expecting this: <div id="wrapper"><div id="full"></div></div>
But it returns "<div id="full"></div>" and not the whole variable.
Use .find("#full") to select the element then remove attribute. The original object retains the value.
var myhtml = $('<div id="wrapper"><div id="full" width="800px"></div></div>');
var newhtml = myhtml.find("#full").removeAttr("width");
console.log($(myhtml)[0].outerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

id is right but not value

i am trying to alert id of a button (which is generated using jquery ) but when i alert its value it not coming right. heres the code
function removeimg(name,btn12){
//make request to remove the name
// $("#" + name).closest('li').remove();
// $("#" + btn12).remove();
// document.getElementById(name).style.display = 'none';
// document.getElementById(btn12).style.display = 'none';
var str = "#" + btn12;
alert(str);
alert($(str).val());
}
here is the link
http://shri-ram.lifekloud.com/pilot/step4.php
when you uplaod a image under the tab "add delete photo" the button is generated
i am trying to alert id of a button
val() does not get the id of an element; val returns the value element.
To get the id of an element, use attr
alert($(str).attr('id'));
Just a stab in the dark from your comment well its not even returning value thts the issue. but the id name is getting displayed correctly
If you have
<input type='button' id='b' value='btn' />
then
alert($('#b').val());
will in fact display btn. That said, if you have
<button id='b'>btn</button>
then nothing will be displayed. But like I said that's just a stab in the dark. It's impossible to know better without the html available (and I'm afraid I don't have time to parse through your site)
You have one meta-character . in your id #btnheader-8878374.png, That is the problem.
Just escape like this
$('.#btnheader-8878374\\.png')
and try you will get your concept working.
Full code,
var str = "#" + btn12;
str = str.replace('.','\\\\');
alert($(str).val());
Your problem is most likely that you do not have the value attribute set on your buttons, thus calling val() returns nothing.
If you want the text of the button just call text().
See jsFiddle
HTML
<button id="btn12">Button 12</button>
JQUERY
var str = "#" + "btn12";
alert( str ); // yields #btn12
alert( $(str).val() ); // yields nothing
alert( $(str).text() ); // yields Button 12

innerHTML not updating display

First, hello everyone as I'm new here.
To summarize my problem, I read the content of an XML file to display in a table.
The basic function to do this works well, I created a derivated function to include a search filter related to an input field.
The search algorithm works well and I'm able to preview the HTML code of the search result using the alert() function and this code seems proper and can be displayed in a browser properly as it would be supposed to. However the innerHTML code of the concerned div is not updated...
I would appreciate any kind of input or solution anyone could provide as I've been stuck on this ! Thanks !
Here is the code :
function printListMod2(){
//Search parameters ?
var searchContent = document.getElementById("searchField").value;
var i=0;
newHTML = "<table id=\"tableInstrus\">";
for (i=0;i<listInstrus.length;i++){
filename = returnFilename(i);
title = returnTitle(i);
tempo = returnTempo(i);
sample = returnSample(i);
multi = returnMulti(i);
style1 = returnStyle1(i);
style2 = returnStyle2(i);
var regEx = new RegExp(searchContent, 'gi');
var resultSearch = title.match(regEx);
if(resultSearch!=null){
if(i%2==0){
newHTML += "<tr class=\"tr0\"><td class=\"idColumn\">"+(i+1)+"</td><td class=\"emptyColumn\"></td><td class=\"nameColumn\">"+title+"</td><td class=\"tempoColumn\">"+tempo+"</td><td class=\"sampleColumn\">"+sample+"</td><td class=\"multiColumn\">"+multi+"</td><td class=\"styleColumn\">"+style1+"</td><td class=\"styleColumn\">"+style2+"</td><td class=\"addLink\"><a id="+filename+" onclick=\"addLinkToPlaylist("+i+")\"><img title=\"Add to playlist\" class=\"addButton\" src=\"images/buttonAdd.png\"/></a></td><td class=\"playLink\"><a onclick=\"playTrack("+i+","+true+")\"><img title=\"Play this track\" class=\"playButton\" src=\"images/buttonPlaySmall.png\"/></a></td></tr>";
}
else{
newHTML += "<tr class=\"tr1\"><td class=\"idColumn\">"+(i+1)+"</td><td class=\"emptyColumn\"></td><td class=\"nameColumn\">"+title+"</td><td class=\"tempoColumn\">"+tempo+"</td><td class=\"sampleColumn\">"+sample+"</td><td class=\"multiColumn\">"+multi+"</td><td class=\"styleColumn\">"+style1+"</td><td class=\"styleColumn\">"+style2+"</td><td class=\"addLink\"><a id="+filename+" onclick=\"addLinkToPlaylist("+i+")\"><img title=\"Add to playlist\" class=\"addButton\" src=\"images/buttonAdd.png\"/></a></td><td class=\"playLink\"><a onclick=\"playTrack("+i+","+true+")\"><img title=\"Play this track\" class=\"playButton\" src=\"images/buttonPlaySmall.png\"/></a></td></tr>";
}
}
}
newHTML += "<tr><td class=\"idColumn\"></td><td id=\"emptyColumn\"></td><td class=\"nameColumn\"></td><td class=\"tempoColumn\"></td><td class=\"sampleColumn\"></td><td class=\"multiColumn\"></td><td></td><td></td></tr>";
newHTML += "</table>";
alert(newHTML); //this displays the HTML code properly
document.getElementById("listDiv").innerHTML = newHTML; //this doesn't seem to do anything...
}
Is your script being executed before the document has finished loading?
Then it won't find #listDiv because the div doesn't exist yet.
I would check the javascript console output for errors and check if the following code doesn't return undefined:
{
...
console.log( document.getElementById('listDiv') );
}

Escape characters in String in a HTML page?

I have a string in the below non-escaped format in a HTML page:
<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>
What I need is to use jQuery/JavaScript to replace that string with just the link "SomeThing".
I have looked at some examples in StackOverflow, but they don't seem to work. I'm just getting started with jQuery and JavaScript, so would appreciate any help here.
Any ideas?
Try html() and text() in jquery to decode:
var str = '<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>';
var decoded = $('<div />').html(str).text();
alert($(decoded).text());
See Fiddle demo
var str = '<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>';
var helper = document.createElement('p');
// evaluate as HTML once, text now "<a href..."
helper.innerHtml = str;
// evaluate as HTML again, helper now has child element a
helper.innerHtml = helper.innerText;
// get text content only ("SomeThing")
alert(helper.innerText);
Here is a possible starting point.
Hope this gets you started!
function parseString(){
var str = '<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>';
var begin = str.indexOf('\">',0)+2; //--determine where the opening anchor tag ends
var end = str.indexOf('</a>',0); //--determine where the closing anchor tag begins
var parsedString = str.substring(begin,end); //--grab whats in between;
/*//--or all inline
var parsedString = str.substring(str.indexOf('\">',0)+2,str.indexOf('</a>',0));
*/
console.log(parsedString);
}
parseStr();

How to find if an ID is present in a variable which has HTML content

Am trying to find if the ID is present in a variable which has HTML content.
ID name is getting attached to DIV element by dynamic variables.
strHTML = "<div id='"+var1+var2+"'>"
Now, i like to check if a particular ID is present in strHTML.
How do i do that.?
Thanks in advance.
EDITED
Added actual code for more clarity...
for(data in ArrayOFObjects)
var splitDate = ArrayOFObjects[data]["NewsDate"].split("-");
**if(!$(strHTML).find('#'+splitDate[1]+splitDate[0]))** // if condition is not correct, just my try
{
strHTML += "<div id='"+splitDate[1]+splitDate[0]+"></div>"
}
}
So when the next for in loop happens, i like to check if the ID already exist in strHTML, if it exists then i do not want the DIV creation to happen
Thanks
If you want to know if your HTML contains an element whose id contains some value, you may do
var $elements = $('[id~="'+someValue+'"]', '<div>'+strHTML+'</div>');
var doContain = $elements.length>0;
If your string strHTML is really something like "<div id='"+var1+var2+"'>", then simply use a regex :
var id = strHTML.match(/["']([^\"']*)["']/)[1];
and look in id for your id.
You can use javaScript's search function:
var n=strHTML.search(var1+var2);
if (n > -1)
{
// found it!
}

Categories