I'm attempting to add +1 (or -1) to a span and then attach the value to the an href.
This is my code:
<script>
$(function () {
var valueElement = $('#value');
function incrementValue(e) {
valueElement.text(Math.max(parseInt(valueElement.text()) + e.data.increment, 0));
calculateLink();
return false;
}
$('#plus').bind('click', { increment: 1 }, incrementValue);
$('#minus').bind('click', { increment: -1 }, incrementValue);
function calculateLink() {
var value1 = document.getElementById('value').innerText;
var value2 = document.getElementById('valueone').innerText;
var value3 = document.getElementById('valuetwo').innerText;
var url = "deskshop3.aspx?item1=" + value1.text + "&item2=" + value2.text + "&item3=" + value3.text;
var element = document.getElementById('cashierLink');
element.setAttribute("href", url)
}
});
Now, what happens is that I am capable of changing the value of "value" span by pressing plus and minus buttons, but whenever I press the href "cashierLink" it always sends the default values of "value", "valueone" and "valuetwo" that the page loaded with.
What am I doing wrong?
Thanks in advance,
Arseney
Your valueElement is getting its text changed first, but then during the calculateLink() call, you are trying to assign a url using value1.text. However, value1 does not have a .text property since it is a string and not an object. This causes an error during execution and ends up bailing out of the code early, which explains why the value element changes visually, yet your href value is incorrect.
Try doing this for your URL instead:
var url = "deskshop3.aspx?item1=" + value1 + "&item2=" + value2 + "&item3=" + value3;
I'm not sure it's the way you wanna do it, but you should try to use global variables instead of text value from an element. I made a JSFiddle to show you what it could look like, you can change it the way you want to.
DEMO
/// global variables ///
var valCount = 0;
var value1 = ['first value', 'second value', 'third value'];
var value2 = ['first 2nd value', 'second 2nd value', 'third 2nd value'];
var value3 = ['first 3rd value', 'second 3rd value', 'third 3rd value'];
////////////////////////
$('#plus').bind('click', function(){ calculateLink(); });
$('#minus').bind('click', function(){ calculateLink(true); });
function calculateLink(minus) {
if(minus){
if(valCount == 0)
valCount = (value1.length-1);
else
valCount--;
} else{
if(valCount == (value1.length-1))
valCount = 0;
else
valCount++;
}
var url = "deskshop3.aspx?item1=" + value1[valCount] +
"&item2=" + value2[valCount] +
"&item3=" + value3[valCount];
document.getElementById('cashierLink').setAttribute("href", url);
}
Related
I have done the dynamic generates textbox based on the number that user type. For example, user types 10 in the input box clicked add will generate 10 input box. I have a label to catch the number.
here is my question
how do I start from 1?
how do I rearrange the number when user remove one of the input boxes
here is my javascript
$(document).ready(function () {
$("#payment_term").change(function () {
var count = $("#holder input").size();
var requested = parseInt($("#payment_term").val(), 10);
if (requested > count) {
for (i = count; i < requested; i++) {
$("#payment_term_area").append('<div class="col-lg-12 product_wrapper">' +
'<div class="col-lg-12 form-group">' +
'<label>' + i + 'Payment</label>' +
'<input type="text" class="payment_term form-control" name="PaymentTerm[]"/>' +
'</div>' +
'cancel' +
'</div>');
}
$("#payment_term_area").on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('.product_wrapper').remove();
calculateTotal();
x--;
})
}
});
});
here is my view
<input type="text" id="payment_term" />
<button onclick="function()">Add</button>
<div id="payment_term_area"></div>
You were nearly there, however, by hardcoding the label's you were making updating them difficult for yourself. I have created a jsfiddle of my solution to your problems. I personally prefer to cache the values of my jQuery objects so that they arent hitting the DOM each time they are referenced, for the performance boost (hence why they are listed at the top). I also, find it nicer to bind the click event in JS rather than using the html attribute onclick, but this is just a preference.
JSFIDDLE
Javascript
// create cache of jQuery objects
var add_payment_terms_button = $('#add_payment_terms');
var payment_term_input = $('#payment_term');
var payment_term_area = $('#payment_term_area');
var default_payment_values = ['first value', 'second value', 'third value', 'forth value', 'fifth value'];
var default_other_value = 'default value';
// bind to generate button
add_payment_terms_button.on('click', generatePaymentTerms);
function generatePaymentTerms(){
var requested = parseInt(payment_term_input.val(), 10);
// start i at 1 so that our label text starts at 1
for (i = 1; i <= requested; i++) {
// use data-text to hold the appended text to the label index
payment_term_area.append(
'<div class="col-lg-12 product_wrapper">' +
'<div class="col-lg-12 form-group">' +
'<label data-text=" Payment"></label>' +
'<input type="text" class="payment_term form-control" name="PaymentTerm[]"/>' +
'</div>' +
'cancel' +
'</div>');
}
// call the function to set the labels
updateProductIndexes();
}
function updateProductIndexes(){
// get all labels inside the payment_term_area
var paymentLabels = payment_term_area.find('.product_wrapper label');
for(var x = 0, len = paymentLabels.length; x < len; x++){
// create jQuery object of labels
var label = $(paymentLabels[x]);
// set label text based upon found index + 1 and label data text
label.text( getOrdinal(x + 1) + label.data('text'));
// either set the next input's value to its corresponding default value (will override set values by the user)
label.next('input.payment_term').val(default_payment_values[x] || default_other_value)
// or optionally, if value is not equal to blank or a default value, do not override (will persist user values)
/* var nextInput = label.next('input.payment_term');
var nextInputValue = nextInput.val();
if(nextInputValue === '' || default_payment_values.indexOf(nextInputValue) >= 0 || nextInputValue === default_other_value){
nextInput.val(default_payment_values[x] || default_other_value)
} */
}
}
// courtesy of https://gist.github.com/jlbruno/1535691
var getOrdinal = function(number) {
var ordinals = ["th","st","nd","rd"],
value = number % 100;
return number + ( ordinals[(value-20) % 10] || ordinals[value] || ordinals[0] );
}
payment_term_area.on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('.product_wrapper').remove();
// after we remove an item, update the labels
updateProductIndexes();
})
HTML
<input type="text" id="payment_term" />
<button id="add_payment_terms">Add</button>
<div id="payment_term_area"></div>
First you have to give id for each label tag ex:<label id='i'>
Then you can re-arrange the number by using document.getElementById('i')
Refer the Change label text using Javascript
hope this will be much helpful
I have an HTML textarea defined in index.html defined as follows:
<textarea id="myTextArea" rows="12" readonly="7" class="form-control"></textarea>
I have a JavaScript file named shared.js. Right now, shared.js only has the following:
function appendToTextArea(id, text, stayOnCurrentLine) {
var current = $(id).val();
var newText = current + ' ' + text;
if (!stayOnCurrentLine) {
newStatus += '\n';
}
$(id).val(newText);
console.log($(id).val());
}
Index.html is successfully referencing shared.js. It even calls appendToTextArea just fine. I'm calling the code from a function in index.html called myButtonClick.
function myButtonClick() {
appendToTextArea('#myTextArea', 'Hello', false);
appendToTextArea('#myTextArea', 'How', false);
appendToTextArea('#myTextArea', 'are', false);
appendToTextArea('#myTextArea', 'you', false);
}
When the above is called, the text of myTextArea is never updated. However, in the console, I see no errors. In addition, I can see the text exactly how I would expect it. What am I doing wrong?
Define newStatus as empty string and concatenate it with outputted string:
function appendToTextArea(id, text, stayOnCurrentLine) {
var current = $(id).val();
var newStatus = "";
var newText = current + ' ' + text;
if (!stayOnCurrentLine) {
newStatus += '\n';
}
$(id).val(newText + newStatus);
console.log($(id).val());
}
-jsFiddle-
I want create a web application that display a list of items. Suppose I have displayed a list view (say listobject1) of 3 items. when clicked on any of them I get new list view (say listobject2) which its value is according to listobject1. When again I click one of them I get another view. Now when I click back button i want to go back to previous list view i.e. when I'm now on listobject2 and again when back button is pressed I want to show listobject1. Can anybody tell me how I can do this in JavaScript?
Edit
I'm still study about the stuff but I can't solve this problem yet. In order to clarify my problem now, here's my code:
$(document).ready(function() {
$("#result").hide();
$("input[name='indexsearch']").live("click", function() {
$("#result").show();
$("#result").empty();
loading_img();
var $textInput = $("[name='valueLiteral']").val();
$.getJSON("get_onto", {
"input" : $textInput
}, function(json) {
if(json.length > 0 ) {
var arrayPredicate = [];
var arrayObject = [];
var arraySubject = [];
$.each(json, function(index, value) {
arraySubject[index] = value.subject;
arrayPredicate[index] = value.predicate;
if(value.objectGeneral != null) {
arrayObject[index] = value.objectGeneral;
} else {
arrayObject[index] = value.objectLiteral;
}
}
);
var stmt = [];
//concat all related array into string (create triple statement)
$.each(arrayPredicate, function(k,v){
stmt[k] = "<span class='subject' id="+arraySubject[k]+">"
+ arraySubject[k] + "</span> " + " -> " + v + " : "+
//change object from text to be button form
"<button class = 'searchAgain-button' name = 'searchMore' \n\
value = " + arrayObject[k] + ">" + arrayObject[k] + "</button><br> <br>";
});
stmt = stmt.sort();
$.each(stmt, function(k,v){
$("#result").append(v);
});
} else {
var $noresult = "No Result : Please enter a query";
$("#result").append($noresult);
}
});
});
$("button").live("click", function() {
$("#result").show();
$("#result").empty();
loading_img();
var $textInput = $(this).attr("Value");
//var $textInput = "G53SQM";
$.getJSON("get_onto", {
"input" : $textInput
}, function(json) {
if(json.length > 0 ) {
var arrayPredicate = [];
var arrayObject = [];
var arraySubject = [];
$.each(json, function(index, value) {
arraySubject[index] = value.subject;
arrayPredicate[index] = value.predicate;
if(value.objectGeneral != null) {
arrayObject[index] = value.objectGeneral;
} else {
arrayObject[index] = value.objectLiteral;
}
}
);
var stmt = [];
var searchMore = "searchMore";
//concat all related array into string (create triple statement)
$.each(arrayPredicate, function(k,v){
stmt[k] = "<span class='subject' id="+arraySubject[k]+">" + arraySubject[k] + "</span> " + " -> " + v + " : "+ " <button class = 'searchAgain-button' name = " +searchMore + " value = " + arrayObject[k] + ">" + arrayObject[k] + "</button><br><br>";
});
stmt = stmt.sort();
$.each(stmt, function(k,v){
$("#result").append(v);
});
} else {
var $noresult = "No Result : Please enter a query";
$("#result").append($noresult);
}
});
});
At first, user only see one button name "valueLiteral". After user perform 1st search, the result is return in a form of JSON and eventually put in stmt[] to display, which at this state the second button was create as a clickable-result which will automatically take the value of result and do second search if user click the second button.
Now the problem is, I want to add a 3rd HTML button name "back" to make the web display the previous result in stmt[] if user click on the button.
Hope this helps in clarify the problems, I'm still doing a hard work on this stuff since I'm a newbie in JavaScript. Appreciate all helps.
This is what you want almost exactly the way you want it.
You'll have to use history.pushState to push these fake events into the history.
Alternatively, you can use location.hash to store the current object, and update the hash every time you display a new list. Then onhashchange find the hash and display the appropriate list.
See http://jsfiddle.net/cFwME/
var history=[new Array(),new Array()];
history[0].id="#back";
history[1].id="#next";
Array.prototype.last=function(){
return this[this.length-1];
}
$('#list>li:not(:first)').click(function(){
if(!history[0].length || history[0].last().html()!=$('#list').html()){
history[0].push($('#list').clone(true,true));
$(history[0].id).prop('disabled',false);
history[1].length=0;
$(history[1].id).prop('disabled',true);
}
$('#list>li:first').html('This is List '+$(this).index());
});
$('#back').click(getHistory(0));
$('#next').click(getHistory(1));
function getHistory(n){
return function(){
if(!history[n].length){return false;}
history[(n+1)%2].push($('#list').replaceWith(history[n].last()));
history[n].pop();
$(history[(n+1)%2].id).prop('disabled',false);
if(!history[n].length){$(history[n].id).prop('disabled',true);}
}
}
Check out jQuery BBQ - http://benalman.com/projects/jquery-bbq-plugin/
i have a problem in preventing duplicates from being entered, i'm generated radio buttons dynamically in 2 pages at the same time using exactly one button, i take the label from the user and generate a radio button from that label, i want to prevent the user from entering 2 identical labels, here's the script which generates radios for the 2 pages any help will be appreciated
function createRadioElement(elem, label, checked) {
var id = 'option1_' + label;
$('#after').append($('<input />', {
'type': 'radio',
'fieldset':'group',
'name': 'option1',
'id': id,
'data-role': 'controlgroup',
'data-theme':'b',
'value': '1'}));
$('#after').append('<label for="' + id + '">'+ label + '</label>').trigger('create');}
function createRadioFortSecondPage(elem, label, checked) {
var id = 'option1_' + label;
$('#Inserthere').append($('<input />', {
'type': 'radio',
'fieldset':'group',
'name': 'option1',
'id': id,
'data-role': 'controlgroup',
'data-theme':'b',
'value': '1'}));
$('#Inserthere').append('<label for="' + id + '">'+ label + '</label>').trigger('create');}
that's the function i wrote to prevent duplicates:
function checkDublicates(){
var isExist=true;
var x = document.getElementById('option').value;
var labels = [];
$('#after input[type=radio]').each(function() {
labels.push($('label[for='+$(this).attr('id')+']').text());
});
for(var i=0;i<labels.length;i++){
if(x==labels[i])
{
isExist=false;}
else{
isExist=true;}
}
return isExist;}
and that's the button action:
$('#AddButton').click(function(){
var exist=checkDublicates();
<!--var isEmpty=validate();-->
<!--if(exist==true){
<!--alert("Duplicates Are Not Allowed!");
<!--}else{
var y=document.getElementById('question').value
document.getElementById('headTitle').innerHTML=y;
if(exist==false){
alert("Duplicates Not Allowed!")
}else{
createRadioElement(this,$('#option').val(),true);
createRadioFortSecondPage(this,$('#option').val(),true);
}
});
Just use $.inArray(val, arr) it will work ! http://api.jquery.com/jQuery.inArray/
But just a comment concerning your code.
Replace
document.getElementById('question').value
by
$('#question').val()
and
document.getElementById('headTitle').innerHTML=y
by
$('#headTitle').html(y)
Will be much cleaner ;-)
You can use this handy function to push elements into an array and check for duplicates at the same time. It'll return true if it catches a duplicate.
var noDupPush = function (value, arr) {
var isDup = false;
if (!~$.inArray(value, arr)) {
arr.push(value);
} else {
isDup = true;
}
return isDup;
};
// You can use it like this
var arr = ['green'];
if (noDupPush('green', arr)){
// Dup exists
}
// Or else it will just push new value to array
You could generate an id that includes the text of the label and then very quickly check for the existence of an element containing that text. For example:
function generateLabelId( userinput ){
return 'awesomelabel_' + userinput.replace(/\W/g,'');
}
var label = document.getElementById(generateLabelId( userinput ));
var labelDoesNotExist = (label == undefined );
if (labelDoesNotExist){
// create your element here
// making sure that you add the id from generateLabelId
}
alert("data going into $hidden: " + selected.data[1]);
hidden.val(selected.data[1]);
alert("data now in $hidden: " + $hidden.val());
What would be a reason that $hidden.val() in the last line above would return undefined? I have verified that selected.data[1] contains an integer value.
Edit #1: Some additional context per comments: ($hidden is a hidden input field)
$.fn.extend({
autocomplete: function(urlOrData, hidden, options) {
var isUrl = typeof urlOrData == "string";
var $hidden = $(hidden);
options = $.extend({}, $.Autocompleter.defaults, {
url: isUrl ? urlOrData : null,
data: isUrl ? null : urlOrData,
delay: isUrl ? $.Autocompleter.defaults.delay : 10,
max: options && !options.scroll ? 10 : 150
}, options);
// if highlight is set to false, replace it with a do-nothing function
options.highlight = options.highlight || function(value) { return value; };
// if the formatMatch option is not specified, then use formatItem for backwards compatibility
options.formatMatch = options.formatMatch || options.formatItem;
return this.each(function() {
new $.Autocompleter(this, options, $hidden);
});
and...
$.Autocompleter = function(input, options, $hidden) {
//...
function selectCurrent() {
var selected = select.selected();
if (!selected)
return false;
var v = selected.result;
previousValue = v;
if (options.multiple) {
var words = trimWords($input.val());
if (words.length > 1) {
v = words.slice(0, words.length - 1).join(options.multipleSeparator) + options.multipleSeparator + v;
}
v += options.multipleSeparator;
}
alert("data going into $hidden: " + selected.data[1]);
$hidden.val(selected.data[1]);
alert("data now in $hidden: " + $hidden.val());
Edit #2: More details.... I'm trying to use the jQuery autocomplete extension on a form with multiple textbox controls (each implement the autocomplete). There's a seperate button on the form beside each textbox that submits the form to a handler function that needs to find the value of the item selected and save it to the db. The way I thought to go about this was to include a hidden field on the form to hold the selected value.
Thanks Paolo Bergantino. I discovered that I wasn't passing the initial hidden in with a # in front of the hidden field id, so $hidden was never getting set properly. It was difficult for me to debug because the the autocomplete is inside an ascx control as an embedded resource. Once I ensured that the value of hidden was including the # it worked properly.
Could $hidden be a checkbox that is not checked?