We inherited some old code which is in place and working. It is a simple pricing switch between £ GBP and $ USD - the price updates onChange as seen below in the pen.
PEN link
https://codepen.io/go6/pen/rNOgaee
$(function() {
$("#curr").on("change",function() {
var curr = this.value;
var prefix = curr=="500"; // or ["usd","yen",...].indexOf(curr); for more
var sign = curr=="500"?"":"";
$(".value").each(function(){
$(this).text(
(prefix?sign:"") +
$(this).data(curr) +
(prefix?sign:"")
);
})
}).change();
});
Question
The price by default is set to USD, as per the data-usd value when the page loads. We want to supply a page URL query string eg /pricing?curr=GBP which can toggle the pricing to GBP.
Tried so far but not working
I have tried a few combinations using this Answer:
Show / Hide elements based on query string value
but so far, none have worked. Please can someone assist in implementing a query string sitch of currency?
Just add this to your code:
if(document.URL.indexOf("curr=GBP") !== -1)
{
$(".value").each(function(){
$(this).text($(this).data("gbp"));
})
$("#curr").val("gbp");
}
Related
I'm having troubles thinking a solution to this problem.
I have this table and a JSON like this one:
{:id=>"e-123",
:subject_initials=>"IN",
:grade=>"12"}
I need to search on the table the id of the person (which in this case is "e-123") and search on the first row the initials of the subject and put the grade on the X and Y position.
The result of the example above should be something like this
Any idea how to do this?
Need to search through the heading inputs to get a column index and search through the user id inputs to get a row index then use eq() method to isolate the one you need to update
var $subjectInput = $('tr').first().find('input').filter(function() {
return this.value === data.subject_initials
});
var $idInput = $('tr').find('td:eq(1) input').filter(function() {
return this.value.toLowerCase() === data.id
});
var colIdx = $subjectInput.parent('td').index();
var rowIdx = $idInput.closest('tr').index();
$('tr').eq(rowIdx).find('td').eq(colIdx).find('input').val(data.grade)
Adding some additional classes on these 2 types of inputs would help make the selectors for finding them easier
If the rows are generated dynamically adding an ID to the row and course name class to the data entry inputs you could simplify the whole thing immensely
<tr id="e-123">
.....
<input class="form-control course_IN">
JS
$('#' + data.id).find('input.course_' + data.subject_initials).val(data.grade)
DEMO
I am displaying an alert box after clicking on a button but the string text is going down.
Here is my code:
jQuery('input[name="addtocart"]').each(function()
{
jQuery(this).on("click", function(event)
{
qty = jQuery(this).parent().find('input[name="qty"]').val();
var qty1 = parseFloat(qty);
qth = jQuery(this).parent().parent().find('.qtyonhand').text();
var qth1 = parseFloat(qth);
itemName = jQuery(this).parent().parent().parent().find('.cell-desc
span').text();
if(qty1 > qth1){
alert("For the following item, the ordered quantity exceeds the
current available quantity.Please adjust the quantity and
retry.\n"+itemName+"-"+"Available Qty:"+qth1);
}
});
});
Here is the image:
In the above image, availability text is displaying on the next line.
How can I display the string in a single line? Please help.
It seems like you need to replace the newlines with spaces.
Add this code before the if statement:
itemName = itemName.replace(/\n/g, " ");
Regex comes from this thread
if(qty1 > qth1){
alert("For the following item, the ordered quantity exceeds the
current available quantity.Please adjust the quantity and
retry."+itemName+"-"+"Available Qty:"+qth1);
}
Please remove the \n from the alert content
I have a category page, where I display different products. In each product I have a section displaying Was Price, Save Price and New Price. Just to illustrate the structure of the Was Price:
<p class="old-price">
<span class="price-label">Was</span>
<span class="price" id="old-price-65848">
<span class="price">
<span class="currency">£</span>
</span>
</span>
</p>
Currently on product page using jQuery I can get the was price and convert it into a number:
var oldPrice = parseFloat(jQuery('.old-price .price .price').first().text().replace(/[^0-9\.]+/g, ""), 10);
And it all works fine on product page where you have only one Was Price block. However when I go to category page I have multiple blocks using the same structure and the same class the above code picks up only the first block and ignores the rest. This can be easily shown using:
console.log(oldPrice, "%");
How can I amend the code so it will pick up all the Was Price on the category page?
Edit:
I've managed to map the old Price and the Save price using the bellow code. However I am trying to execute math function where the condition is :
var oldPrices = jQuery('.old-price .price .price').map(function(){
return parseFloat(jQuery(this).text().replace(/[^0-9\.]+/g, ""), 10);
}).get();
var specialPrices = jQuery('.special-price .price .price').map(function() {
return parseFloat(jQuery(this).text().replace(/[^0-9\.]+/g, ""), 10);
}).get();
var youSave = specialPrices / (oldPrices / 100);
Unfortunately it returns NaN value
PS: All the prices are dynamically generated.
Thanks
You can map it to get an array:
var oldPrices = jQuery('.old-price .price .price').map(function(){
return parseFloat($(this).text().replace(/[^0-9\.]+/g, ""), 10);
}).get();
console.log(oldPrices);
That's said, you'd have better to set a data-* attribute to handle old price specific to each element, e.g: <p class="old-price" data-old-price="12345">.
And btw, your snippet seems unrelevant with your posted HTML markup, there is no old price value to retrieve there except maybe regarding the ID attribute.
Sorry for the noobish question but, I am trying to build a form summary that will populate a div (immediately) with all of the fields being used. Here is a small sample of the field: Fiddle
For some reason the JS is not working as I would expect it to, can anyone point out what I am doing wrong?
For example, I would like it to output: "AND name: john EXCEPT number 222".
I would also like to be able click on a result to remove it, and clear the field. Thank you
$(".allS").change(function () {
if ($(this).next('.textArea').not(':empty'))
// varible to hold string
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("#text_here").text(str);
}).change();
$('.textArea').change(function(){
var $inputs = $('form#form :input[type="text"]'),
result = "";
$inputs.each(function(){
// access the individual input as jQuery object via $(this)
result += $(this).val()+"<br>";
});
// store result in some div
$('div#text_here').text(result);
}).change();
There were many mistakes in your code. I simplified it to a very short code that only does what's needed to get the output you requested. Here's the working fiddle.
$(".allS, .textArea").change(function () {
var str = '';
if ($('#name').val().length > 0 && $('#number').val().length > 0)
var str = $('#nameMod>option:selected').text() + ' name:' + $('#name').val() + ' ' + $('#numberMod>option:selected').text() + ' number ' + $('#number').val();
$("#text_here").html(str);
});
Basically, what this does is attach a change event handler to both classes (.alls, .textArea), and when the event is triggered, both input fields are tested for any content. If this test passes, a string is composed out of all the relevant values, and the div content is set. If the test failed (no content), the str variable contains an empty string and the div is cleared.
Just glancing at the code, the selector 'form#form :input[type="text"]' looks wrong. For starters, input is not a pseudoclass. Also, attribute matching shouldn't have the quotes.
This may or may not be what you want (I think it is, from looking at your html):
'form#form input[type=text]'
Also your <br>'s are not working because you called text(). call html() instead.
I was wondering if anyone can help? What I am trying to do is retrieve the word count from javascript code into a form and then pass it into php along with the rest of the form which will check that the word count is a certain length or else it won't be submitted.
The javascript is as follows.
counter = function() {
var value = $('#msg').val();
if (value.length == 0) {
$('#wordCount').html(0);
$('#totalChars').html(0);
$('#charCount').html(0);
$('#charCountNoSpace').html(0);
return;
}
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
var totalChars = value.length;
var charCount = value.trim().length;
var charCountNoSpace = value.replace(regex, '').length;
$('#wordCount').html(wordCount);
$('#totalChars').html(totalChars);
$('#charCount').html(charCount);
$('#charCountNoSpace').html(charCountNoSpace);
};
$(document).ready(function() {
$('#count').click(counter);
$('#msg').change(counter);
$('#msg').keydown(counter);
$('#msg').keypress(counter);
$('#msg').keyup(counter);
$('#msg').blur(counter);
$('#msg').focus(counter);
});
My problem is returning wordCount into a hidden field in a form. I am not too good with javascript and am not sure how to modify this code to make it work. The rest I can figure out but am stuck here. Thank you for your help, it is greatly appreciated.
$('#wordCount').val(wordCount);
$('#totalChars').val(totalChars);
$('#charCount').val(charCount);
$('#charCountNoSpace').val(charCountNoSpace);
Use .val() instead of .html(), because .val() refers to the value of an input field.
Your HTML inside the form should include a hidden input field:
<input type="hidden" id="word_count" name="word_count" value="0" />
Then inside your JS:
$('#word_count').val(wordCount);
All together embedded inside your function:
counter = function() {
var value = $('#msg').val();
if (value.length == 0) {
$('#wordCount').html(0);
$('#totalChars').html(0);
$('#charCount').html(0);
$('#charCountNoSpace').html(0);
return;
}
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
var totalChars = value.length;
var charCount = value.trim().length;
var charCountNoSpace = value.replace(regex, '').length;
$('#wordCount').html(wordCount);
$('#word_count').val(wordCount);
$('#totalChars').html(totalChars);
$('#charCount').html(charCount);
$('#charCountNoSpace').html(charCountNoSpace);
};
$(document).ready(function() {
$('#count').click(counter);
$('#msg').change(counter);
$('#msg').keydown(counter);
$('#msg').keypress(counter);
$('#msg').keyup(counter);
$('#msg').blur(counter);
$('#msg').focus(counter);
});
If you have INPUT fields in your form, use val()
$('#wordCount').val(wordCount)
That would work for a field like this:
Be aware that there's a difference between "id" and "class". jQuery allows you to select elements based on their properties. The "id" property gets selected with "#", just like you'd do it in CSS. So make sure you have that "id='wordCount'" defined in your hidden field.
Have a look at this http://www.hscripts.com/scripts/JavaScript/word-count.php
There are plenty of examples online, just google "javascript count words in textbox"
Some imporntant notes:
A very long string with no spaces is still 1 word so don't forget to set the max length for fields
If you are doing this as a sort of validation be aware of the fact that you can not trust a form field because it can be easily manipulated, so don't forget to check the word count on the server side after the form is submitted.
The Code that you are showing is not just javascript it also includes jquery, please make sure you included jquery
<script src = "http://code.jquery.com/jquery-1.11.1.min.js"></script>
$('#field').val('asdf'); //Sets Value of a input type="text"
$('#field').html('sadf'); //Sets the html of a div
Using javascript you use either value for a input or innerHtml for a div or other text based element
document.getElementById('field').value = 'asdfsadf';
document.getElementById('field').innerHtml= 'asdfsadf';
Also instead of using a form submit consider using jquery $.ajax(there is nothing wrong with form submits but there are benefits to knowing jquery as well such as you came make async requests
http://api.jquery.com/jquery.ajax/
You will want to use a hidden field such as the following and have it in the form
<form id="myform" action='posttome.php'>
<input type="hidden" id="wordCount"/>
<input type="submit" value="sbumit"> //Submits Form
</form>
Then set its value by using of of three methods, a an elements html, an elements value, or a javascript variable $('#wordCount').val()
$('#wordCount').val($('#wordCountSoruceDiv').html()); // Sets the value to another divs html
$('#wordCount').val($('#wordCountSourceInput').val()); // Sets the value to another inputs value
$('#wordCount').val(wordCountVariable); // Sets the value to a variable