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
Related
I have input sliders in social context where many people can input to the same slider.
I have set the initial position to be in the middle signifying that the user hasn't input anything. And when the user inputs their value I want to show both their input value and the average of all the input values.
I'm able to save all values and show the average but I want to show two thumbs instead of just the average.
I'm using the bootstrap custom range. The avgValue is calculated after getting ajax data from another function. Actually this function is called inside the function that gets ajax data and at the end html variable is passed to be displayed with the whole article.
function showValues(data) {
var html = "", edit = false, avgValue = 50;
for (let i = 0; i < data.values.length; i++) {
var value = data.values[i];
avgValue += Number(value.value)/data.value.length;
if (values._id == window.user._id){edit = true};
// //set second thumb to show value
}
html += '<span class="" onclick="setValue(this);" data-id="' + data._id + '">';
html += '<input type="range" class="custom-range" id="customRange" value="' + avgValue + '" />';
html += '</span>';
return html;
}
data.values is an array with objects for each value along with the id of the user who has input the value.
{
"_id": user._id,
"value": value
}
The function that sets the value and saves it in monogodb is here
function setValue(self) {
var _id = self.getAttribute("data-id");
var value = self.childNodes[0].value;
var ajax = new XMLHttpRequest();
ajax.open("POST", "/setValue", true);
ajax.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// var response = JSON.parse(this.responseText);
// //set second thumb to show value
}
};
var formData = new FormData();
formData.append("accessToken", localStorage.getItem("accessToken"));
formData.append("_id", _id);
formData.append("value", value);
ajax.send(formData);
}
Do I need to use some other kind of range slider other than bootstrap custom range or can this be modified to my needs? How do I add a second thumb with user's actual value and show it alongwith the average?
I simplify my problem to a minimum because in reality my code is very long and complex to explain.
I have two text input fields, in the first field I can insert a series of values, while the second field receives the values of the first field and compares them with those it already has. if there are double values the function warns and the user can choose whether to overwrite them or delete them, otherwise the value is added.
I want to do this through a for loop.
function prova() {
var stringa_valoredainserire = document.getElementById("valoredainserire").value;
var stringa_valoredacambiare = document.getElementById("valoredacambiare").value;
var stringa_valoredacambiare2 = document.getElementById("valoredacambiare");
mioarray = stringa_valoredainserire.split("; ");
var i, len, text;
//inizio ciclo for
for (i = 0, len = mioarray.length, text = ""; i < len; i++) {
if (stringa_valoredacambiare.indexOf(mioarray[i]) !== -1) {
if (confirm('il valore ' + mioarray[i] + ' esiste, ok per sovrascriverlo, annulla per cancellarlo')) {
stringa_valoredacambiare2.value = stringa_valoredacambiare.replace(mioarray[i], mioarray[i]);
} else {
stringa_valoredacambiare2.value = stringa_valoredacambiare.replace(mioarray[i] + '; ', '');
}
} else {
stringa_valoredacambiare2.value = stringa_valoredacambiare2.value + mioarray[i] + '; ';
}
}
}
<input id="valoredainserire" value="" type="text">
<input id="valoredacambiare" value="pere; cipolle; mele; " type="text" readonly>
<input type="button" onclick="prova();" value="Prova">
the problem is that if the values to be entered in the first input field are equal to the values of the second, if I wanted to delete them, the function only deletes the last one, because it is the last variable that keeps it in memory.
how can I remedy this situation? some idea? Thanks in advance.
I have html markup like this
<input type="hidden" value="" id="shortcode_selected_package" name="shortcode_selected_package">
<div class="selected-packages-wrap">
<div class="shortcode-wrap">
<a class="data-remove" href="#" data-id="417" data-name="Test New Packs">-</a><label>Test New Packs</label>
<span class="checkbox-wrap">
<span><input type="checkbox" value="5">10 GB</span>
<span><input type="checkbox" value="26">Sony</span>
</span>
</div>
<div class="shortcode-wrap">
<a class="data-remove" href="#" data-id="220" data-name="New custom pack">-</a><label>New custom pack</label>
<span class="checkbox-wrap">
<span><input type="checkbox" value="5">10 GB</span>
<span><input type="checkbox" value="25">Unlimited Calls</span>
</span>
</div>
</div>
Here you can see in the first div element there are two checkbox with value 5, 26 (10 GB and Sony). So when someone check the checkbox of first div ten its value should be added with its parent value in the shortcode_selected_package div.
So lets say when user check both 10 GB and Sony then the value of the div should be like this
417[5|26]
if user checks the checkbox for the 2nd div then the value should be like this
417[5|26],220[5,25]
But if user unchecks any checkbox then its value should be remove from the set value. Like if user unchecks Unlimited Calls from the 2nd div then the value should be like
417[5|26],220[5,25]
I have tried this code but the values are not updating
$('body').on('click', '.selected-packages-wrap input[type=checkbox]', function() {
var PackageSelected = $('input#shortcode_selected_package').val();
var selectedVal = this.value;
var ParentId = $(this).parents('.shortcode-wrap').find('a.data-remove').attr('data-id');
if( this.checked ) {
selectPackage(ParentId, selectedVal, PackageSelected);
}
else {
unselectPackage(ParentId, selectedVal, PackageSelected);
}
});
function selectPackage(ParentId, selectedVal, PackageSelected) {
Packages = PackageSelected.split(',');
var Arr = [];
if(jQuery.inArray(ParentId, Packages) !== -1) {
$.each( Packages, function( key, val ) {
if( val == ParentId ) {
Packages[key] = val.replace(val, val + '[' + selectedVal + ']');
Arr.push(Packages);
}
});
console.log(Arr[0]);
}
}
First, I think that you should put the data-id of the link as a checkbox attribute or better yet at each div holding the checkboxes (it will be more convienient for selection instead of doing:
.parents('.shortcode-wrap').find('a.data-remove').attr('data-id');
)
Then what you do is every time on change or on click of any of the checkboxes you loop through the divs with class of shortcode wrap.
$('.selected-packages-wrap input[type=checkbox]').on('change', function() {
var checkboxes_data = [];
// Loop through the divs
for(var divs_count = 0; divs_count < $('.shortcode-wrap').length; divs_count++) {
checkboxes_data[divs_count] = {div_id: $('.shortcode-wrap:eq(' + divs_count + ')').attr('data-id'), checkboxes_id: [],}
// Loop through the checkboxes
for(var chBox_count = 0; chBox < $('.shortcode-wrap:eq(' + divs_count + ') input[type=checkbox]').length; chBox_count++) {
var $.current_checkbox = $('.shortcode-wrap:eq(' + divs_count + ') input[type=checkbox]:eq(' + chBox_count + ')');
// If the checkbox is checked add the value to the array
if($.current_checkbox.is(":checked")) {
checkboxes_data[divs_count].checkboxes_id.push($.current_checkbox.val()
}
}
}
var final_value = '';
// Goes trough the the newly created array adds the div value followed by the corresponding checkboxes value
checkboxes_data.forEach(function(div) {
var checkbox_ids = div.checkbox_ids.join(", ");
final_value += div.div_id + '[' + div.checkbox_ids + '], ';
});
$('#shortcode_selected_package').val(final_value);
});
I'm trying to change the text of a button to that of a value stored in a variable. The button is currently blank and not even using a fixed value like .value = "test"; is working.
HTML:
<div id="addContainer">
<textarea id="listTitleInput" class="textarea" placeholder="Add the title of your list here, then click 'Add List'." rows="10" cols="50"></textarea>
<button id="addListBtn" data-role="button">Add List</button>
</div>
<div id="listDisplayContainer">
</div>
JS:
$(document).ready(function () {
//LISTS
var listTitleInput = document.getElementById("listTitleInput");
var addListBtn = document.getElementById("addListBtn");
var listCount = localStorage.getItem("listCount");
if (listCount === null) {
noteCount = 0;
}
//ADD LISTS
function addList() {
if ($("#listTitleInput").val() == "") {
alert("Please give your list a title, then click 'Add List'.");
} else {
listCount++;
var list = $("#listTitleInput").val();
console.log("List Count: " + listCount);
console.log(list);
var display = document.createElement("button");
document.getElementById("listDisplayContainer").appendChild(display);
display.className = "ui-btn";
display.id = "list" + listCount;
$("#list" + listCount).value = list;
}
}
//Lists
addListBtn.addEventListener("click", addList);
});
Looks like you need to change $("#list" + listCount).value = list; to $("#list" + listCount).text(list);
value is not a property and val() doesn't work for a button.
The problem is that you are confusing native DOM attributes with jQuery ones.
$("#list" + listCount).value = list;
$("#list" + listCount) is a jQuery object so it doesn't use the native javascript properties that you may be used to. (value=)
What you are looking for is:
$("#list" + listCount).html(list);
Or
$("#list" + listCount).text(list);
Since list is a string value, it will be best to use .text
I have three text inputs :
First name
Last Name
User Name
In the form I have only these inputs are of type: text.
I want each one of them to be at least 4 characters long so I decided to validate them together.
I want to use Jquery to display an error message that is red when the length is less than 4 and green when it is greater.
I put three error messages respectively with the following Ids:
flength
llength
ulength
(the first letter corresponds to the input , example first name : flength and so on)
so here is my code to do this:
$('input [type= text]').keyup(function ({
var l = $(this).val();
var x = l.id;
x = x.charAt(0);
x = '#' + x + 'length';
if (l.length < 4) {
$(x).removeClass('valid').addClass('invalid');
} else {
$(x).removeClass('invalid').addClass('valid');
}
});
Why wouldn't this script work? what should I modify?
Edit
demo
After seeing your comments
changing var x = $(this).attr("id"); wont fix the problem too
since $(this).attr("id") gives your current element id and your current element is your input tag element and you did not set the id attribute, Instead you have set it to div tags as you have mentioned in your comments, since you are trying to retrieve id attribute which you have not set and your getting an error.
One solution I could give is this way
<input type="text" name="flength"/> // set name attribute same as div ids
<input type="text" name="llength"/>
<input type="text" name="ulength"/>
$('input[type=text]').keyup(function ({
var l = $(this).val(); // get the input string
var x = $(this).attr('name'); // get the current input element name attribute
if (l.length < 4) {
$('#' + x).removeClass('valid').addClass('invalid');
} else {
$('#' + x).removeClass('invalid').addClass('valid');
}
});
Check this http://jsfiddle.net/Q2y8m/4/
Try this
$(document).ready(function () {
$('input[type=text]').keyup(function () {
var l = $(this).val();
var x = $(this).attr('id'); // notice it is not l.id
x = x.charAt(0);
x = '#' + x + 'length';
if (l.length < 4) {
$(x).removeClass('valid').addClass('invalid');
} else {
$(x).removeClass('invalid').addClass('valid');
}
});
});
Demo http://jsfiddle.net/3yqVg/2/
Try to change var x = l.id; width var x = $(this).id;