How to append an element inside a "<button>" - javascript

I am trying to append an Icon to a button, the challenge that I am facing at the moment is that the icon retuns as a string (I see the code I wrote for the Icon).
I've tried changing qoutations marks, I've also tried putting the Icon tag inside a span and a div but it hasn't helped.
HTML code that displays the icon and carries the value the determines the icon
<button type="button" id="btnState" name="btnState" class="btn btn-primary btnState" value="<?php echo $pref; ?>"><?php echo "<span class='spnDash'>".$pref."</span>";?></button>
The code the loops though the results and selects the icon that will be displayed
var status = document.getElementsByClassName('btnState');
var i;
for(i =0; i < status.length; i++){
var j = status[i].value;
if(j === 1){
$(".spnDash").remove();
//$("<i class='far fa-thumbs-down'></i>").appendTo(".btnState");
status[i].append('<i class="far fa-thumbs-up"></i>');
}
The Jquery code scans/checks for a value(1/0/-1) delivered from a server and then assigns an icon according to the value e.g. 1 = thumbs up, -1 = thumbs down, 0 = neutral.

status is a DOM Collection object. You're trying to append a string to a object. Hence you're getting a string output.
You can use:
status[i].innerHTML+="<i class='far fa-thumbs-up'></i>";
Or, if you want to use append(), you have to create a DOM object and do as follows:
var obj = document.createElement("i");
obj.classList = "far fa-thumbs-up";
status[i].append(obj);

try using document.getElementById('btnState') and try not to use name attribute

Related

Update text on button using JavaScript

Have such button on my page (for showing current total in shopping cart):
<div class="col s2 offset-s4 valign" id="shoppingCart">
<a class="waves-effect waves-teal btn-flat no-margin white-text right" th:inline="text"><i class="material-icons right">shopping_cart</i>[[#{${total}+' руб'}]]</a>
</div>
Written function for updating total number on that button:
function updateShoppingCart(newTotal) {
var $div = $("#shoppingCart");
var $a = $("<a class='waves-effect waves-teal btn-flat no-margin white-text right'></a>");
var $i = $("<i class='material-icons right'>shopping_cart</i>");
var $string = formatDecimal(newTotal,',','.') + " руб";
$a.append($i);
$a.append($string);
$div.children().remove();
$div.append($a);
}
But it does not work. Please help find bug or what I'm doing wrong.
It's a lot more efficient to set $div = $('#shoppingCart');; in the global scope and use that var instead. This way your JS won't search through your entire DOM every time the function is called.
Your stuff doesn't work because your vars are very odd. I believe what you want to achieve is this:
HTML
<a class="waves-effect waves-teal btn-flat no-margin white-text right" th:inline="text">
<i class="material-icons right">shopping_cart</i>
<span>[[#{${total}+' руб'}]]</span>
</a>
JS:
function updateShoppingCart(newTotal) {
var $div = $("#shoppingCart");
var $a = $("a", $div); //select the <a> within the shoppingcart div
var $i = $("i", $div); //select the <i> within the shoppingcart div
var $span = $("span", $div); //select the newly added span
var newPrice = formatDecimal(newTotal,',','.') + " руб";
$span.text(newPrice);
}
I kept the $a and $i in as examples, but I don't see a need for you to use them or completely replace them, since you only want to change the text. By using a span, you can target the price without replacing all the html.
On a sidenote, the $ is generally used to state a var is a jquery object. string is not a jquery object in this scenario, so the $ there is a bit odd.
On a sidenote, if you want to replace html within an element, you should try doing it like so:
function updateShoppingCart(newTotal) {
var $div = $("#shoppingCart");
var newPrice = formatDecimal(newTotal,',','.') + " руб";
//Create the new HTML as a string, not as an element
var newHtml= '<i>Shopping_cart</i>'+newPrice+'';
//empties div beforehand current html, no seperate removal needed.
//Then places the html string within the element
$div .html(newHtml);
}
See working JSFiddle here

Change a image when list box selected item is changed

I have a list box with id of 'availmap' containing filename of images the path is maps/image.jpg
I also have a image control with id of 'map' that I would like to change to the selected image using the onclick event of the list box
this is the js I have tried and can not figure out why it won't work
<script type="text/javascript">
function ChgImg() {
var list = document.getElementById('availmap');
var indx = list.selectedIndex;
var img = list[indx].value;
var id = document.getElementById('map');
id.src="maps/" + img;
}
This is the image tag and the listbox code
<div id='avail' style='position:fixed;left:500px;top:0;z-index:0;text-align:center;bgcolor='#00b0e6';>
<span style='position:fixed;left:540px;top:30px;width:250px;font-family:Arial;font-size:15px;background-color:#00b0e6;border: 1px #000000 solid;'>Availible Maps</span> </div>
<form action='jobs.php' target='joblist' style='position:fixed;left:500px;top:101px;'></td>
<select id='availmap' name='availmap' size='10' style='width: 250px;position:fixed;left:540px;top:51px;' onchange='ChgImg()'>
EOY;
while($row = mysqli_fetch_array($mapresult))
{
echo "<option value=\"".$row['ID']."\">".$row['AssocMap']."</option>\n ";
}
echo "</select>";
echo "</form>";
echo "<img id='map' src='' alt='' style='position:absolute;left:800px;top:30px;width:260px;height:185px;border: 1px #000000 solid;'>";
I'm sure it is something relatively simple I am missing here
You should use Element.setAttribute()
Adds a new attribute or changes the value of an existing attribute on
the specified element.
element.setAttribute(name, value);
Params
name is the name of the attribute as a string.
value is the desired new value of the attribute.
So, change your code to this:
function ChgImg() {
var list = document.getElementById('availmap');
var indx = list.selectedIndex;
var img = list[indx].value;
var id = document.getElementById('map');
id.setAttribute("src", img);
You're javascript was almost correct, just use id.src=img;
Complete javascript:
function ChgImg() {
var list = document.getElementById('availmap');
var indx = list.selectedIndex;
var img = list[indx].value;
var id = document.getElementById('map');
id.src=img;
}
I would use the change event instead of the click event. Don't forget to add the code in the head of the page.
UPDATE
The javascript you're using works fine as you can see in the working example. However, I don't think you're passing a valid value for the src of the image in the code you provide (value=\"".$row['ID']."\). It seems you're using the ID of the row for the value (usually a number) when you actually need to use a valid src for the image (for example http://www.w3schools.com/images/w3schools_green.jpg). Do you have the url of the images stored in some other column of the row? If so, use it instead of $row['ID']
Also, please check your HTML. There are a few mistakes that you should correct (most of them single quotes badly closed).
I've also modified your html a bit in the example

Dynamically creating unique link or button for each result of a database query result

Basically, a list of results from a database query is inserted into a ul. I want the user to be able to click the result they are looking for and then have one of two things happen:
A unique link is created (such as a php GET request) using the ID of
the selected result
A JS function is called via the onClick
attribute, and the ID of the clicked result is sent as an argument.
The code below is what I have done so far - minus the functionality that I listed above.
The list as it is in the HTML:
<ul data-role="listview" id="treesUL" data-inset="true" style="visibility: hidden">
<li id="treesLI">
<div class="resultNames">
<span class="donorName">Donor</span>
for
<span class="honoreeName">Honoree</span>
</div>
<div class="resultInfo">
<span class="treeName">common</span>
on:
<span class="donationDate">Date</span>
</div>
<div class="resultDedication">
<span class="dedicationText">Dedication</span>
</div>
</li>
</ul>
The javascript that edits the list, based on the results of the query which is stored in the myTrees array. This function is called via a XMLHttpRequest object.
function showTreeContent()
{
if (requestObj.readyState == 4) //Request completed
{
//Retrieve the JSON encoded array, which is stored at index-key: media
var text = requestObj.responseText;
//alert(text);
var myTrees = jQuery.parseJSON(text).media;
$('#treesUL').text('');
//Alert the number of rows, for testing purposes
alert(myTrees.length + " results.");
//Loop through the JSON array, and add each element to a <li>, which is then added to the <ul>
for(var i = 0; i < myTrees.length; i++)
{
var tree = myTrees[i];
var li =$('#treesLI').clone();
li.removeAttr('id');
li.appendTo('#treesUL');
//li.find('.treeLink').setAttribute("href", "somelink url");
li.find('.donorName').text(tree['donor']);
li.find('.honoreeName').text(tree['honoree']);
li.find('.dedicationText').text("'" + tree['dedication'] + "'");
if (tree['common'] != '')
li.find('.treeName').text(tree['common']);
else
li.find('.treeName').text("Unknown Species");
li.find('.donationDate').text(tree['date']);
li.data('treeID','tree'+i);
}
}
}
I tried surrounding the contents of the li tag with an a tag, and then editing the href of the a tag, but I was unable to get that to work. I'm using jQuery Mobile for this project also. Let me know if you need any more information - any help is greatly appreciated!
First thing that I see strange is that you are calling $('#treesUL').text(''); that deletes the contents of the ul and than in the loop you request $('#treesLI') which was deleted above.
What i would do is create the HTML as a string and append it to the ul.
Example.
var html = '';
for(var i = 0, length = myTrees.length; i < length; ++i)
{
var tree = myTrees[i];
html += '<li class="treesLI" onClick="somefunction('+ tree.id+')">';
html += '<div class="resultNames"><span class="donorName">' + tree.donor + '</span>';
html += 'for <span class="honoreeName">'+ tree.honoree + '</span></div>';
html +='</li>';
$('#treesUL').append(html);
}
As you can see i added an onClick handler that calls a function that receives a parameter.
You can use that onClick function to make a GET request with $.axaj()
If you don't want to use onClick you can do:
$('#treesUL li').click(function(event){
});
Some other observations:
You can access the properties of an object using the . like this tree.dedication.
You should do your for like this for(var i = 0, length = myTrees.length; i < length; ++i)
it is 2 times faster in IE8

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

Pass variables to code <input type="image" src="imageSrc;" >

hope someone can help a noob. Many thanks in advance.
I have an index page with links to hundreds of other pages holding song words.
I have built each song page but it would be MUCH simpler to have one MASTER page that took a variable from the index page and found the corresponding words (which exist as png graphics.)
I have sorted Step 1 - I can pass a variable from the index page to the master page using:
<a href="javascript: window.open('MUSIC/beatles/mastertest2.html?song=ER', '_parent')">
where song=ER is the variable to display the words for Eleanor Rigby. For Step 2, I can also retrieve that information in the master page with:
var imageSrc = (qs("song")+".png"); document.write(imageSrc);
which will display the text ER.png which is the name of the image I want to display.
For Step 3 I am trying to get this same variable read into:
<input type="image" src="imageSrc;">
to display the picture. I have searched this and other forums for days now and nothing suggested works for me. I could be missing out an essential early step in the coding?
Update:
My master html file has this code to retrieve the variable:
function qs(search_for) {
var query = window.location.search.substring(1);
var parms = query.split('&');
for (var i=0; i<parms.length; i++) {
var pos = parms[i].indexOf('=');
if (pos > 0 && search_for == parms[i].substring(0,pos)) {
return parms[i].substring(pos+1);;
}
}
return "";
}
And it uses this code to disply the variable (appended with .png) just to prove to me that it is getting through:
var imageSrc = (qs("song")+".png");
document.write(imageSrc);
Then I am trying to feed the variable into a routine to display the png selected. The next script doesn't work but I am thrashing about trying anything right now:
var imageSrc = (qs("song")+".png");
document.write(imageSrc);
<input type="image" src="#imageSrc;" border="0" value="Notes" onClick="placeIt(); showIt()">
<input id="song-image" type="image">
var imageSrc = 'ER.png';
var input = document.getElementById('song-image');
input.src = imageSrc;
If you have already <input type="image"> in your HTML page, you must add an id and then set it's src attribute with
HTML:
<input id="song-image" type="image">
JS:
var imageSrc = 'http://www.lorempixel.com/200/100';
var input = document.getElementById('song-image');
input.src = imageSrc;
JSFiddle for testing.
If I understood you right, its very simple. Are you looking for this?
var input = document.createElement('input');
input.type = 'image';
input.src = imageSrc;
document.body.appendChild(input);
If you can print the variable imageSrc using document.write, then you can use it like shown above.

Categories