The following script returns the name and text from inputs and drop downs and adds them to a text area. I need to remove the names (of each input/drop downs) from each of the values returned but I'm having no luck? the = have already been removed.
<script>
$('#formt').find('select,input[type="text"]').not('#tagt').change(function(){
var val = "";
var tags = '';
$('form select,input[type="text"]:not("input#tagt")').each(function(){
if ($.trim(this.value).length > 0 ) {
val += ($(this).attr('name') + "" + this.value + "");
}
})
$('#tagt').val(tags+val);
});
$('#submit').click(function(){
window.location= $('#tagt').val();
});
</script>
So just remove the part where it gets the name, as in $(this).attr('name')
$('#formt').find('select,input[type="text"]').not('#tagt').change(function(){
var val = "";
$('form select,input[type="text"]:not("input#tagt")').each(function(){
val += this.value;
})
$('#tagt').val(val);
});
Related
I basicly add my input values to vals array.
Then save the array to localStorage: localStorage.setItem('mylist', JSON.stringify(vals));
After that, i show values from vals array.
It saves the values to localStorage but when i refresh, values doesn't show up on screen with my dynamicly created li elements.
Why?
Note: I want to use localstorage with JSON.
JSFIDDLE
var input = document.getElementById("input");
var box = document.querySelector(".box");
var vals = [];
var li;
var list;
input.addEventListener("keyup", function(e) {
var val = e.target.value;
if (e.which == 13) {
box.innerHTML = "";
input.value = " ";
// Push input value array
vals.push(val);
localStorage.setItem('mylist', JSON.stringify(vals));
// Loop input values
list = vals.map(function(item, index) {
li = document.createElement("LI");
box.appendChild(li);
li.innerHTML = JSON.parse(localStorage.getItem('mylist'))[index];
});
}
}, false);
box.innerHTML = list;
After a page refresh the list array is empty. this will fix it:
var vals = JSON.parse(localStorage.getItem('mylist') || "[]");
vals.forEach(function(entry) {
li = document.createElement("LI");
box.appendChild(li);
li.innerHTML = entry;
})
The || "[]" is a fallback in case localStorage returns null (the user never set a list)
You should also remove the last line of your script ( box.innerHTML = list; )
Youd don't read anything from localStorage after page load. You read data from storage only in your keyup handler but you do it right after overriding it with new value. You have to get data from storage when page is loaded:
use this:
var list = JSON.parse(localStorage.getItem('mylist'))
It is saving in localStorage but in your code, after you refresh, you never populate the values in your HTML.
var input = document.getElementById("input");
var box = document.querySelector(".box");
var storageVals = localStorage.getItem('mylist');
var vals = storageVals ? JSON.parse(storageVals) : [];
input.addEventListener("keyup", function(e) {
var val = e.target.value;
if (e.which == 13) {
box.innerHTML = "";
input.value = " ";
// Push input value array
vals.push(val);
localStorage.setItem('mylist', JSON.stringify(vals));
renderList();
}
}, false);
function renderList() {
// Loop input values
vals.forEach(function(item, index) {
var li = document.createElement("LI");
box.appendChild(li);
li.innerHTML = JSON.parse(localStorage.getItem('mylist'))[index];
});
}
renderList();
I am trying to add a br sign in a input text field if it has more than 5 letters.(while writing)
My Code creates br signs after 5 letters, but it creates for than 1 br sign.
Code:
(function(i){
$('#input' + i).on('keyup', function() {
if($('#input' + i).val().length > 5) {
$('#input' + i).val($('#input' + i).val() + '<br>');
}
});
}(i))
I strongly recommend not doing this (seem comments on the question).
But if you really want to, use input, not keyup, remove previous <br> markers you've added, and break up the whole string rather than just appending at the end. See comments:
(function(i) {
$('#input' + i).on('input', function() {
// No need to look it up repeatedly, remember the jQuery wrapper for this input
var $this = $(this);
// Get the value
var val = $this.val();
if (val.length > 5) {
// Remove old <br>s
val = val.replace(/<br>/g, "");
// Add new ones
var result = "";
while (val) {
result += val.substring(0, 5);
val = val.substring(5);
if (val) {
result += "<br>";
}
}
// Set the value
$this.val(result);
}
});
}(0))
<input type="text" id="input0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have a form field that is being duplicated / removed dynamically
See the fiddle here : http://jsfiddle.net/obmerk99/y2d4c/6/
In this feature, I also need to increment the NAME of the field ( and ID etc.. ) like so :
o99_brsa_settings[brsa_dash_wdgt_content][0]
o99_brsa_settings[brsa_dash_wdgt_content][1]
o99_brsa_settings[brsa_dash_wdgt_content][2] ...
It is working, but the problem is that when I add / remove fields , when it gets to the last ( actually first one ) , it will give me "undefined" and will not add anymore fields .
To see the problem you will need to "play" a bit with add/remove .
I believe the main problem is how to keep all of those on the same array level if we have [0] and [0][2]
I am far from a JS guru, and this code was somehow assembled from various sources. But I am kind of stuck right now, So any help will be appreciated .
Try this way:
$(function () {
$(".addScnt").on("click", function () {
var i = checkNumberOfElements();
var scntDiv = $("div[id^='widget_dup']:last");
var prevDiv = scntDiv.clone();
var newname = $(prevDiv).find("textarea").attr("name").substring(0, $(prevDiv).find("textarea").attr('name').indexOf(']'));
prevDiv.find('textarea').attr('name', newname + "][" + i + "]");
prevDiv.find('textarea').attr('id', newname + "][" + i + "]");
prevDiv.find('label').attr('for', newname + "][" + i + "]");
prevDiv.attr('id', $(prevDiv).attr('id') + "_" + i);
$(scntDiv).after(prevDiv);
});
$(document).on("click", ".remScnt", function (event) {
var i = checkNumberOfElements();
if (i <= 1) {
return false;
} else {
var target = $(event.currentTarget);
target.parent("div").remove();
}
});
});
function checkNumberOfElements() {
// Number of textareas
var i = $("textarea[name^='o99_brsa_settings[brsa_dash_wdgt_content]']").length;
// Number of divs
// var i = $("div[id^='widget_dup']").length;
if (typeof i === undefined) {
return 0;
} else {
return i;
}
}
Demo: http://jsfiddle.net/y2d4c/7/
I make a dynamic form, if i delete a row then in loop result is NaN of the deleted element i want when i delete element its 0 value pass not NaN. Like i delete 5th element when 1=5 it shows NaN. How to remove this error and instead 0 will be add in sum value, how i do?
$("body").on('change', '.quantity', function() {
var that = $(this);
if ($('#itemcounter').val()==""){
$('#itemscounter').val("1");
var counter=$('#itemscounter').val();
var quantity=$('#quantity').val();
var unitprice=$('#unitprice').val();
var linetotal=quantity*unitprice;
that.parent().find('.linetotal').val(linetotal)
$("#invoicetotalamount").val(+linetotal)
var discount=document.getElementById('discount').value ;
var discountamount= discount/100 * linetotal;
var amount=linetotal-discountamount;
$("#balanceamount").val(+amount);
} else {
var counter=$('#itemscounter').val();
var quantity=$('#quantity').val();
var unitprice=$('#unitprice').val();
var linetotal=quantity*unitprice;
$('#linetotal').val(+linetotal);
var sum=linetotal;
for (i = 2; i <=counter; i++) {
var quantity=parseFloat($('#quantity' + i).val());
var unitprice=parseFloat($('#unitprice' + i).val());
var linetotal=quantity*unitprice;
$('#linetotal' + i).val(+linetotal);
alert(sum);
sum=+sum +(+(linetotal));
}
$("#invoicetotalamount").val(+sum);
var discount=document.getElementById('discount').value ;
var discountamount= discount/100 * sum;
var amount=sum-discountamount;
$("#balanceamount").val(+amount);
}
});
Check the value if its a number like this:
var quantity=parseFloat($('#quantity' + i).val());
if(isNaN(quantity)){
quantity=0;
}
you can check it with if else loop for dynamic data:
var str_val = $('#itemscounter').val();
if(str_val == NaN){
str_val =0; //use str_val at the place you want
alert(str_val);
}
You can check to see if it's NaN
var quantity = !isNaN($('#quantity' + i).val()) ? parseFloat($('#quantity' + i).val(), 2) : 0;
I am creating an app in which i am using jquery mobile autocomplete. To create the listview i am calling a function in js file. When a user enter the character in the input field it will call the js file and then i want to call another function which is return to access the data from data base and it will create and array object and this created array i want to pass back to the function called and then it will create an li base on that array.
Here is the code inside the demoautocomplete.js
function createlist(autocomplete_name){
var objdata=['user_name','user_id'];
$( "#"+autocomplete_name).on("listviewbeforefilter", function ( e, data ) {
var autocompleteData=new Array();
var $ul = $( this ),
$input = $( data.input ),
value = $input.val(),
html = "";
$ul.html( "" );
getdatafromtable(autocompleteData,value); var dataarray=getdatafromtable(autocompleteData);
if ( value && value.length > 1 )
{
$.mobile.loading('hide');
for(var j=0;j<dataarray.length;j++)
{
html +="<li id='"+dataarray[j].id+"'>"+dataarray[j].user_name+"</li>";
}
$ul.html( html );
$ul.listview( "refresh" );
$ul.trigger( "updatelayout");
$.mobile.activePage.find('input[placeholder="Find a name..."]').attr('id','autocomplete');
}
$("ul>li").click(function()
{
var textval=$(this).text();
var id=$(this).attr('id');
$('#autocomplete').val(textval);
$.mobile.activePage.find("[data-role=listview]").children().addClass('ui-screen-hidden');
storeselectedid(id,autocompleteData);
});
});
}
function getdatafromtable(autocompleteData,value){
db.transaction(function(tx){
$.mobile.loading('show');
var selectQuery='select first_name||" "||last_name user_name,user_id from users where first_name like "%'+value+'%" or last_name like "%'+value+'%" limit 10';
var selectQuery1='select account_name user_name,account_id from crm_account where account_name like "%'+value+'%" limit 10';
tx.executeSql(selectQuery,[],function(tx,results){
var dataset=results.rows;
if(dataset.length>0){
for(var i=0;i<dataset.length;i++)
{
var item=dataset.item(i);
var element = new Object();
element['id']=autocomplete_name+"_"+i;
for(var j=0;j<objdata.length;j++)
{
element[objdata[j]]=item[objdata[j]];
}
autocompleteData[i]=element;
}
return autocompleteData;
}
});
}); }
here the script code in html from where js will be called:
$(function(){
<ul id="autocomplete" data-role="listview" data-inset="true" data-filter="true" data-filter-placeholder="Find a name..."
data-filter-theme="d" >
</ul>
var autocomplete=$(document.createElement('ul')).attr('id',autocomplete_name);
autocomplete.attr('data-role','listview');
autocomplete.attr('data-inset',true);
autocomplete.attr('data-filter',true);
autocomplete.attr('data-filter-placeholder','Find a name');
autocomplete.appendTo("#contentDemo");
createlist(autocomplete_name); });
when getdatafromtablefunction is called it should create fill the data in the array object and pass that arrayobject back to the createlistfunction and then if loop should be executed.
here is the flow of code how it should work :
1. the page is loaded then when user enters a character in the input field.
2.it will go to thejs file then input value is assign to value variable. which i want to pass to the function getdatafromtable so base o that input it fetch the data from the database.
3.the retrive is stored in the array object than its pass back to the function from where it was called.
4.After retriving the array data it should create the li listview.
Any help is appreciated.
Thanks in advance.
Assuming your getdatafromtable function is properly made to return the array
var data_array = getdatafromtable(autocompleteData);
and in your getdatafromtable function you should have a return statement returning an array
Also dont name your variable the same as an already existing function. autocompleteData in this case is both a local variable and a function name.
Edit:
$("#" + autocomplete_name).on("listviewbeforefilter", function (e, data) {
var autocompleteData = new Array();
var $ul = $(this),
$input = $(data.input),
value = $input.val(),
html = "";
$ul.html("");
getdatafromtable(autocompleteData, $ul, $input, value, html);
});
function after_data_retrieved(autocompleteData, $ul, $input, value, html) {
if (value && value.length > 1) {
$.mobile.loading('hide');
for (var j = 0; j < dataarray.length; j++) {
html += "<li id='" + dataarray[j].id + "'>" + dataarray[j].user_name + "</li>";
}
$ul.html(html);
$ul.listview("refresh");
$ul.trigger("updatelayout");
$.mobile.activePage.find('input[placeholder="Find a name..."]').attr('id', 'autocomplete');
}
$("ul>li").click(function () {
var textval = $(this).text();
var id = $(this).attr('id');
$('#autocomplete').val(textval);
$.mobile.activePage.find("[data-role=listview]").children().addClass('ui-screen-hidden');
storeselectedid(id, autocompleteData);
});
}
function getdatafromtable(autocompleteData, $ul, $input, value, html) {
db.transaction(function (tx) {
$.mobile.loading('show');
var selectQuery = 'select first_name||" "||last_name user_name,user_id from users where first_name like "%' + value + '%" or last_name like "%' + value + '%" limit 10';
var selectQuery1 = 'select account_name user_name,account_id from crm_account where account_name like "%' + value + '%" limit 10';
tx.executeSql(selectQuery, [], function (tx, results) {
var dataset = results.rows;
if (dataset.length > 0) {
for (var i = 0; i < dataset.length; i++) {
var item = dataset.item(i);
var element = new Object();
element['id'] = autocomplete_name + "_" + i;
for (var j = 0; j < objdata.length; j++) {
element[objdata[j]] = item[objdata[j]];
}
autocompleteData[i] = element;
}
}
after_data_retrieved(autocompleteData, $ul, $input, value, html);
});
});
}