Targetting and Changing HTML content using jQuery - javascript

I'm trying to change the "10" in the HTML below using jQuery:
<div id="ingredients">
<h2>Ingredients</h2>
<h4>Sugar: <span class="sugar">10</span></h4>
Here have been the iterations that I've gone through that have been unsuccessful:
$(document).ready(function() {
$('#ingredients.sugar').html("5");
});
and
$(document).ready(function() {
$('span[class=sugar]').html("5");
});
In addition, how would I store the value of "10" in a variable? I'm trying to do this:
var $sugar = $('#ingredients.sugar').html();
Would that work?
Thanks!
Henry

Try:
$(document).ready(function() {
$('#ingredients .sugar').html("5");
});
Notice the space between; this says look for a .sugar child from the #ingredients parent. You should also be able to do:
var val = $('#ingredients .sugar').html();

You have missed space in your selector, this will work:
$('#ingredients .sugar').html("5");

Here's a version with a simplified selector (don't need #ingredients), factory caching and update without using quotes (5 works fine).
// Document ready
$(function () {
var $sugar = $( '.sugar' ), // Cache jQuery factory
originalValue = $sugar.html(); // Cache original value
// Update value
$sugar.html( 5 );
});

Related

jQuery reset star-rating.js

I am using this plugin https://danielupshaw.com/jquery-star-rating/
I want to reset my form. But how can I reset these stars??
$("#btn-reset").on('click', function() {
//some other inputs reset
$('#starrating').star_rating.remove();
$('#starrating').star_rating.reload();
}
Please help on how to reset these stars to zero or null.
Here is the full code.
$("#btn-reset").on('click', function() {
$('#starrating').star_rating.reload();
});
jQuery(function($) {
$('#starrating').star_rating({
click: function(clicked_rating, event) {
event.preventDefault();
$('input[name=\'rating\']').val(clicked_rating);
this.rating(clicked_rating);
}
});
});
I don't know if this is the best approach, since I'm not familiar with this library...
But I achieved a reset like this:
$(document).ready(function(){
$('.rating').star_rating();
$("#resetStars").on("click",function(){
$(".rating").remove();
$('.star-rating').replaceWith("<span class='rating'>0/10 stars</span>");
$(".rating").text("0/10").star_rating();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://danielupshaw.com/jquery-star-rating/jquery.star-rating.js"></script>
<h1>This is a good script!</h1>
<span class="rating">9.5/10 stars</span><br>
<br>
<br>
<button id="resetStars">Reset stars</button>
I'm not familiar with the plugin, but looking at the link you provided, can't you just update the text inside of the element to reflect an empty or zero rating? Something like:
$("#btn-reset").on('click', function() {
$('#starrating').text('0/5').star_rating();
}
It looks like all you need to do is set the content to 0. Then re initialize the method.
$("#starrating").html("0");
$("#starrating").star_rating();
You could try something like this; an attempt to set default blank stars on initial page load, or Click.
$(document).ready(function() {
$('i').addClass('fa-star-o');
});
Then refresh page to rest:
$( ".reset" ).click(function() {
location.reload();
});
If you don't want to refresh page, you could try:
$( ".reset" ).click(function() {
$('i').addClass('fa-star-o');
});
You may have to re-initiate your click feature on the star with similar jQuery to re add the appropriate Class when needed.
If this doesn't help or work; could you create a https://jsfiddle.net/ to fully replicate your issue; and then we could solve it. If it were me; I'd find a better plugin to use or just write it from scratch at that point.
A bit another approach by re-rendering your rating stars from scratch using custom renderRating function.
HTML:
<div class="rating-stars"></div>
<button class="reset-rating">Reset rating</button>
JS:
var defaultRating = "0/5";
renderRating("3/5");
function renderRating(rating) {
var ratingEl = $('<span />').addClass('rating');
var ratingStr = rating || defaultRating;
ratingEl.text(ratingStr);
$('.rating-stars').html(ratingEl);
ratingEl.star_rating();
}
$('.reset-rating').on('click', function() {
renderRating();
})
Preview on JSFiddle
This should reset it to 0:
$('#starrating').star_rating('rating', 0);
Here's the format to call the public methods:
$('#starrating').star_rating('method_name');
Should your click event be inside the document ready? If it is outside document ready, that can sometimes cause issue. I hope this helps :)

Where do I put $(this) in the function?

Since I want to use classes instead of id's in these functions(I have three of the same function with different things I want to .append) I am sure I need to put $(this) in those functions somewhere to only trigger only ONE function on button click and not all three of them. but I am not sure because I am a total beginner in jquery/js, so I would appreciate some help.
$(document).ready(function () {
$(".onclick").click(function () {
$('#favorites').append('<div data-role="main"class="ui-content"><div class="ui-grid-b"><div class="ui-block-a">Arrow</div><div class="ui-block-b">More Info</div><div class="ui-block-c">Unfavorite</div></div></div>');
});
});
http://codepen.io/anon/pen/JYxqEw - HTML And the Jquery Code
$('.onclick') selects all the elements with a class of onclick. That means that, whenever something with class="onclick" is clicked, that function will fire.
If you want all of those elements to append that exact HTML to the #favorites element, then you can leave your code as-is.
However, if what you're trying to do is append that html to the clicked element, that is when you'd use $(this) -- that selects the element you clicked with jQuery, then you can append directly to that element ie:
$(document).ready(function () {
$(".onclick").click(function () {
// this will append the HTML to the element that triggered the click event.
$(this).append('<div data-role="main"class="ui-content"><div class="ui-grid-b"><div class="ui-block-a">Arrow</div><div class="ui-block-b">More Info</div><div class="ui-block-c">Unfavorite</div></div></div>');
});
});
EDIT
so to insert the contents of each .onclick into #favorites, you'll need to use the innerHTML value of the DOM node. example fiddle:
http://jsbin.com/qazepubuzu/edit?html,js,output
When you select something with jQuery, you're actually getting back not just the DOM node, but a jQuery object -- this object contains both a reference to the actual DOM node ([0]), as well as a jquery object ([1]).
So to select the DOM node with $(this), you target the node: $(this)[0]. Then you can use .innerHTML() to grab the HTML contents of the node and do as you like.
Final result:
$(function () {
$('.onclick').click(function () {
$('#favorites').append( $(this)[0].innerHTML );
});
});
So the building blocks are not that complex, but I think you're a novice jQuery developer and so you may not be clear on the difference between jQuery and JS yet.
$(selector, context) allows us to create a jQuery collection for a CSS selector which is the child of a current context DOM node, though if you do not specify one there is an automatic one (which is document.body, I think). Various functions iterating over jQuery collections make the particular element available as this within the JavaScript. To get to the strong element from the .onclick element in the HTML fragment you need to travel up in the hierarchy, then to the appropriate element. Then, we can collect the text from the element. We can do this in either JS or jQuery.
To do this with simply jQuery:
// AP style title case, because Chicago is too crazy.
var to_title_case = (function () { // variable scope bracket
var lower_case = /\b(?:a|an|the|and|for|in|so|nor|to|at|of|up|but|on|yet|by|or)\b/i,
first_word = /^(\W*)(\w*)/,
last_word = /(\w*)(\W*)$/;
function capitalize(word) {
return word.slice(0, 1).toUpperCase() + word.slice(1).toLowerCase();
}
function capitalize_mid(word) {
return lower_case.exec(word) ? word.toLowerCase() : capitalize(word);
}
return function to_title_case(str) {
var prefix = first_word.exec(str),
str_minus_prefix = str.slice(prefix[0].length),
suffix = last_word.exec(str_minus_prefix),
center = str_minus_prefix.slice(0, -suffix[0].length);
return prefix[1] + capitalize(prefix[2]) + center.replace(/\w+/g, capitalize_mid)
+ capitalize(suffix[1]) + suffix[2];
};
})();
$(document).ready(function() {
$(".onclick").click(function () {
var text = $(this).parents('.ui-grid-a').find('.ui-block-a').text();
var html = '<div data-role="main"class="ui-content">'
+ '<div class="ui-grid-b"><div class="ui-block-a">'
+ to_title_case(text) + '</div><div class="ui-block-b">More Info</div>'
+ '<div class="ui-block-c">Unfavorite</div></div></div>';
$("#favorites").append(html);
});
});

Javascript Selector for custom Tag

I need to be able to get the .val() of a custom parameter within an tag. The tag looks like this:
option style="font-weight: normal" answerid="32" >text here< /option
For the sake of the code / tag being self explanatory, I wanted to use "answerid" instead of "name" but I can't figure out how to get the value of that. My current script looks like this:
<script>
$('select').change(function () {
var optionSelected = $(this).find("option:selected");
var valueSelected = optionSelected.val("answerid");
$.get("ticket.php?do=quickanswer&selected=" +valueSelected+ "",
function( data ) {
$( ".quickanswer" ).html( data );
});
console.log(valueSelected);
});
</script>
You can use .attr():
var valueSelected = optionSelected.attr("answerid");
Fiddle Demo
Using answerid as an attribute is invalid HTML. Instead of using invalid markup, use a custom [data-*] attribute:
<option data-answer-id="32">text here</option>
You can then take advantage of jQuery's .data() method to access the value:
answerId = optionSelected.data('answerId'); //32
.attr() works as well:
answerId = optionSelected.attr('data-answer-id'); //'32'
Please see my related answer for details as to why you'd use one over the other

how to get outerHTML with jquery in order to have it cross-browser

I found a response in a jquery forum and they made a function to do this but the result is not the same.
Here is an example that I created for an image button:
var buttonField = $('<input type="image" />');
buttonField.attr('id', 'butonFshi' + lastsel);
buttonField.val('Fshi');
buttonField.attr('src', 'images/square-icon.png');
if (disabled)
buttonField.attr("disabled", "disabled");
buttonField.val('Fshi');
if (onblur !== undefined)
buttonField.focusout(function () { onblur(); });
buttonField.mouseover(function () { ndryshoImazhin(1, lastsel.toString()); });
buttonField.mouseout(function () { ndryshoImazhin(0, lastsel.toString()); });
buttonField.click(function () { fshiClicked(lastsel.toString()); });
And I have this situation:
buttonField[0].outerHTML = `<INPUT id=butonFshi1 value=Fshi src="images/square-icon.png" type=image jQuery15205073038169030395="44">`
instead the outer function I found gives buttonField.outer() = <INPUT id=butonFshi1 value=Fshi src="images/square-icon.png" type=image>
The function is:
$.fn.outer = function(val){
if(val){
$(val).insertBefore(this);
$(this).remove();
}
else{ return $("<div>").append($(this).clone()).html(); }
}
so like this I loose the handlers that I inserted.
Is there anyway to get the outerHTML with jquery in order to have it cross-browser without loosing the handlers ?!
You don't need convert it to text first (which is what disconnects it from the handlers, only DOM nodes and other specific JavaScript objects can have events). Just insert the newly created/modified node directly, e.g.
$('#old-button').after(buttonField).remove();`
after returns the previous jQuery collection so the remove gets rid of the existing element, not the new one.
Try this one:
var html_text = `<INPUT id=butonFshi1 value=Fshi src="images/square-icon.png" type=image jQuery15205073038169030395="44">`
buttonField[0].html(html_text);
:)
Check out the jQuery plugin from https://github.com/darlesson/jquery-outerhtml. With this jQuery plugin you can get the outerHTML from the first matched element, replace a set of elements and manipulate the result in a callback function.
Consider the following HTML:
<span>My example</span>
Consider the following call:
var span = $("span").outerHTML();
The variable span is equal <span>My example</span>.
In the link above you can find more example in how to use .outerHTML() plug-in.
This should work fine:
var outer = buttonField.parent().html();

jQuery: copying element attributes to another attribute of the same element

I've got a list of links, all in the same class, each with a custom argument ("switch-text"). My script should copy the text of the custom argument to the text of each link and replace it ("Pick A" should become "Pick A Please").
It works fine with only 1 link, but when I add several, they all get switched to the first argument. ("Pick B" should be replaced by "Pick B Please", but it doesn't).
I could probably solve this using each(), but I'm preferably looking for a simple, single jQuery line that does it, and I'm baffled I haven't yet found out how to achieve this.
Can somebody help? Thanks!
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$(".switcher").text( $(".switcher").attr("switch-text") );
});
</script>
Pick A<br>
Pick B<br>
You should use each to go through all the elements, and use this to always act on the current one.
$(document).ready(function() {
$(".switcher").each(function(){
$(this).text( $(this).attr("switch-text") );
});
});
Demo
Without jQuery
you need:
Dean Edwards document ready
getElementsByClassName
Code:
readyList.push(function() {
var els = getElementsByClassName("switcher");
for ( var i = els.length; i--; ) {
els[i].innerHTML = els[i].getAttribute("switch-text");
}
});
And change Dean's script to execute functions on document.ready:
function init() {
// ...
// do stuff
for ( var i = 0; i < readyList.length; i++ ) {
if ( typeof readyList[i] === "function" ) {
readyList[i]();
}
}
//..
}
That's it. You've saved a lot of bandwidth. :)
Demo without jQuery

Categories

Resources