Jquery insert values of text-field into list-box.? - javascript

I want to fetch value from the textfield and add to the listbox.
Here is my jquery code
JS:-
{
$('#btn_AddToList').click(function(
{
var select = document.getElementById('lst_Regions');
var region = $('#txt_RegionName').val();
if('' != region)
{
var newOption = document.createElement('option');
newOption.text = region;
newOption.value = region;
if($.browser.msie)
{
select.add(newOption);
}
else
{
select.add(newOption, null);
}
}
return false;
});
});
here is my html code
html:
<input type="text" name="region" id="txt_RegionName" /><br />
<input type="button" name="add" id="btn_AddToList" value="add" class="btn btn-success" /></br />
<select size="10" id="lst_Regions" style="width: 500px;">
</select>
question: I cannot add the value of the txt_RegionName to the lst_Region ,where i am going wrong?
Thank you.

$('#btn_AddToList').click(function () {
var val = $('#txt_RegionName').val();
$('#lst_Regions').append('<option>' + val + '</option>');
$('#txt_RegionName').val('').focus();
})
jsFiddle example

you can do this like:
$('#btn_AddToList').click(function(event)
{
var region = $('#txt_RegionName').val();
if(region && !$('#lst_Regions>option[value=' + region + ']').length){
var newOption = $('<option value="' + region + '">' + region + '</option>');
$('#lst_Regions').append(newOption);
}
//return false;
event.preventDefault();
event.stopPropagation();
});
just to let you know, you can prevent it from duplicate values using:
$('#lst_Regions>option[value=' + region + ']').length
which has to be zero, and as you see I have added that to my answer.

{
$('#btn_AddToList').click(function()
{
var select = document.getElementById('lst_Regions');
var region = $('#txt_RegionName').val();
if ('' != region) {
$(document.createElement('option')).text(region).val(region).appendTo(select);
}
return false;
});
};

Related

Trying to add new form fields for additional data and getting weird return

I have a jquery script that is supposed to create new table and input fields with a _1 for the new data field. The code does add the table and the fields however the input fields have this when doing a view source of the code.
I am not sure why I am getting [object Object]1 for the form fields.
Also if I add an additional table the other fields get this.
visitor_first_name_NaN where this should be 2 or 3
I am sure I am missing something just not sure what. If anyone has an idea or a fix it would be great.
<script type='text/javascript'>//<![CDATA[
jQuery(document).ready(function(){
jQuery("##visitorRegFrm").validate({
errorElement : "div",
errorPlacement: function(error, element) {
error.appendTo( element.parent("td") );
}
});
});
var arr = new Array();
arr[#qrStaff.currentrow#] = new Array();
arr[#qrStaff.currentrow#][1] = '#qrStaff.Staff_Last_Name#';
arr[#qrStaff.currentrow#][2] = '#qrStaff.Staff_Email#';
arr[#qrStaff.currentrow#][3] = '#qrStaff.Staff_First_Name#';
function changeEmp(obj){
//console.log(jQuery(obj).val());
jQuery('##employee_last_name').val(arr[jQuery(obj).val()][1]);
jQuery('##employee_email').val(arr[jQuery(obj).val()][2]);
jQuery('##employee_first_name_text').val(arr[jQuery(obj).val()][3]);
}
jQuery.format = function(source, params) {
if ( arguments.length == 1 )
return function() {
var args = jQuery.makeArray(arguments);
args.unshift(source);
return jQuery.validator.format.apply( this, args );
};
if ( arguments.length > 2 && params.constructor != Array ) {
params = jQuery.makeArray(arguments).slice(1);
}
if ( params.constructor != Array ) {
params = [ params ];
}
jQuery.each(params, function(i, n) {
source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
});
return source;
};
jQuery(window).on('load',function(){
incdecVar = 1;
jQuery(function() {
var scntDiv = jQuery('##addTable');
var i = jQuery('##addTable table').size + 1;
jQuery('##addNewVistor').on('click', function() {
jQuery('<table class="newTbl" width="100%" border="0" cellpadding="4" cellspacing="5"><tr><td colspan="4"><h3>Visitor Information</h3>Remove</td></tr><tr><td width="25%">First Name:<span class="verror"></span></td><td width="25%"><input type="text" name="visitor_first_name_' + i +'" value="" class="required"/></td><td width="20%">Last Name:<span class="verror"></span></td><td width="30%"><input type="text" name="visitor_last_name_' + i +'" value="" class="required"/></td></tr><tr><td>Title:<span class="verror"></span> </td><td><input type="text" name="visitor_title_' + i +'" value="" class="required"/></td><td>Company:<span class="verror"></span> </td><td><input type="text" name="visitor_company_' + i +'" value="" class="required"/></td></tr><tr><td>Phone:</td><td><input type="text" name="visitor_phone_' + i +'" value=""/></td><td>Email:<span class="verror"></span> </td><td><input type="text" name="visitor_email_' + i +'" value="" class="email"/></td></tr></table>').appendTo(scntDiv);
jQuery('input##Counter').replaceWith('<input type="hidden" name="Counter" id="Counter" value="'+ i +'" />');
newValue = parseInt(jQuery('input##Counter').val())+1;
jQuery('input##Counter').val(newValue);
incdecVar += newValue;
i++;
return false;
});
jQuery('##remNewVisitor').on('click', function() {
if( i > 2 ) {
jQuery(this).parents('.newTbl').remove();
newValue = parseInt(jQuery('input##Counter').val())-1;
jQuery('input##Counter').val(newValue);
incdecVar -= newValue;
i--;
}
return false;
});
});
});//]]>
</script>

how to serialize a form under specific conditions

Taka a look at this fiddle here this is a form where a business user enters the offered services.I sent the data with ajax and by serializing the form.
Click edit and add(plus sign) a service...in the example an input is added where it's name attribute value is of this **form= form[5]...**contrast with this with the form of the name attribute value in the other inputs...only the newly added services have the name attribute like this and the reason for that is to serialize only these...and not the others already present in the DOM/stored in the DB.
And now my problem:
Imagine that the user goes to edit the already registered services(or that he goes to edit them and add a new one)...at this case the already registered services wont'be serialized cause of the form the name attribute value has...(and the reason for this is explained above).
What can I do in this case?Sometimes I must serialize only part of a form and sometimes whole of the form.If all the inputs have name attribute value of form[1....] then along with the newly added input...already registered services will be serialized again.
Thanks for listening.
Code follows(you can see it in the fiddle too)
$('.editservices').click(function() {
//console.log(('.wrapper_servp').length);
originals_ser_input_lgth = $('.services').length;
var originals = [];
$('.show_price')
// fetch only those sections that have a sub-element with the .value
class
.filter((i, e) => $('.value', e).length === 1)
// replace content in remaining elements
.replaceWith(function(i) {
var value = $('.value', this).data('value');
var fieldsetCount = $('#serv').length;
var index = fieldsetCount + i;
return '<div class="show_price"><p id="show_p_msg">Price
visibility</p></div>' + '\
<div class="show_p_inpts">' +
'<input class="price_show"' + (value == 1 ? "checked" : "") + '
type="radio" name="form[' + index + '][price_show]" value="1">yes' +
'<input class="price_show"' + (value == 0 ? "checked" : "") + '
type="radio" name="form[' + index + '][price_show]" value="0">no' +
'</div>'; // HTML to replace the original content with
});
$('#buttons').removeClass('prfbuttons');
$('#saveserv').addClass('hideb');
$('.actionsserv').removeClass('actionsserv');
priceavail = $(".price_show:input").serializeArray();
});
$('#addser').on('click', function() {
$('#saveserv').css('border','2px solid none');
var serviceCount = $('input.services').length + 1;
var serv_inputs = '<div class="wrapper_servp"><div class="serv_contain">\n\
<input placeholder="service" class="services text" name="form[' + serviceCount + '][service]" type="text" size="40"> \n\
<input placeholder="price" class="price text" name="form[' + serviceCount + '][price]" type="text" size="3"></div>';
var p_show = '<div class="show_p">' +
'<p id="show_p_msg">Price visibility;</p>' +
'<span id="err_show_p"></span><br>' +
'</div>';
var inputs = '<div class="show_p_inpts">' +
'<input class="price_show" type="radio" name="form[' + serviceCount + '][price_show]" value="1">yes' +
'<input class="price_show" type="radio" name="form[' + serviceCount + '][price_show]" value="0">no' +
'</div></div>';
$('.wrapper_servp').last().after(serv_inputs + p_show + inputs);
$('#saveserv').removeClass('hideb');
$('#remser').css('display', 'inline');
});
$('#cancelserv').click(function(e) {
e.preventDefault();
//var newinputs = $('.wrapper_servp').length;
//var inp_remv = newinputs - originals_ser_input_lgth;
//$('.wrapper_servp').slice(-inp_remv).remove()
$('.show_p_inpts')
.filter((i, e) => $('.price_show:checked', e).length === 1)
.replaceWith(function(i) {
var value = $('.price_show:checked').attr('value');
return '<span data-value="' + value + '" class="value">' + (value == 1 ? "yes" : "no") + '</span>'
});
});
var groupHasCheckedBox = function() {
return $(this).find('input').filter(function() {
return $(this).prop('checked');
}).length === 0;
},
inputHasValue = function(index) {
return $(this).val() === '';
};
$('#saveserv').click(function(e) {
e.preventDefault();
//from here
var $radioGroups = $('.show_p_inpts');
$('.show_p_inpts').filter(groupHasCheckedBox).closest('div').addClass("error");
$('.services, .price').filter(inputHasValue).addClass("error");
//to here
var $errorInputs = $('input.services').filter((i, e) => !e.value.trim());
if ($errorInputs.length >= 1) {
console.log($errorInputs);
$('#err_message').html('you have to fill in the service'); return;
}
if ($('input.price').filter((i, e) => !e.value.trim()).length >= 1) {
$('#err_message').html('you have to fill in the price'); return;
}
});
var IDs=new Array();
$('body').on('click', '#remser', function(e){
var inputval=$('.services:visible:last').val();
if(inputval!=='')
{r= confirm('Are you sure you want to delete this service?');}
else
{
$('.wrapper_servp:visible:last').remove();
}
switch(r)
{
case true:
IDs.push($('.services:visible:last').data('service'));
$('.wrapper_servp:visible:last').addClass('btypehide');
if($('.serv_contain').length==1)$('#remser').css('display','none');
$('#saveserv').removeClass('hideb').css('border','5px solid red');
//originals.servrem=true;
break;
case false:var i;
for(i=0;i<originals.ser_input_lgth;i++)
{
$('input[name="service'+i+'"]').val(services[i].value);
$('input[name="price'+i+'"]').val(prices[i].value);//εδω set value
}
$('.services').slice(originals.ser_input_lgth).remove();
$('.price').slice(originals.ser_input_lgth).remove();
$('.openservices').addClass('hide').find('.services,.price').prop('readonly', true);
var text='<p class="show_price">Θες να φαίνεται η τιμή;<span data-value="'+ show_pr_val.value +'" class="value">' +(show_pr_val.value==1 ? 'yes':'no') + '</span></p>';
$('.show_p_inpts').remove();
$('.show_price').replaceWith(text);;
break;
}
});
I have an Idea for you. What you can do is when you show the currently existed value in you html instead of giving name attribute just give data-name attribute. I.e
Change this
<input class="services text" data-service="21" size="40" value="hair" type="text" name="service0" readonly="">
To This
<input class="services text" data-service="21" size="40" value="hair" type="text" data-value="hair" data-name="service0" readonly="">
Now when user update this values you can bind an event in jQuery like below.
$(document).ready(function(){
$(".services input").on("change paste keyup", function() {
if($(this).val() === $(this).attr("data-value"))
{
$(this).removeAttr("name");
}else{
$(this).attr("name",$(this).attr("data-name"));
}
});
});
By this way you can give name attribute to only those elements whose values are changed. Now each time you can serialize the whole form and it will only get the value of changed elements.
Don't forget to give unique class to already existed elements so you can bind on change event. Hope its clear to you.

I want to remove an array item when generated check box checked

I made a todolist which is taking value from input and add an item from array so when the given value shown in page i want to remove an item form array whn checkbox checked.
Html part :
<input type="text" id="field" placeholder="Type name" />
<button type="submit" onclick="insertitem()">Submit</button>
<p id="para"></p>
javascript part:
var list = [];
var input;
function insertitem() {
input = document.getElementById('field').value;
list.push(input);
DisplayItem(list);
document.getElementById('field').value='';
}
function DisplayItem(data) {
var contain = document.getElementById('para');
contain.innerHTML='';
for ( var i in data) {
contain.innerHTML +="<div><input id='box' onClick='remove()' type='checkbox' /><label>" + data[i] + "</label></div>";
}
}
function remove() {
var check = document.getElementById('box').value;
for ( var i in list) {
if (list[i]!= check) {
}
}
}
Try this with pure javascript :
Array.splice and Array.indexof()
Add with checkbox inside the label tag.
And click event change with remove(this).Then easly find the label
text and match with list array.
contain.innerHTML +="<div><label><input id='box' onClick='remove(this)' type='checkbox' />" + data[i] +
"</label></div>";
}
var list = [];
var input;
function insertitem() {
input = document.getElementById('field').value;
list.push(input);
DisplayItem(list);
document.getElementById('field').value='';
}
function DisplayItem(data) {
var contain = document.getElementById('para');
contain.innerHTML='';
for ( var i in data) {
contain.innerHTML +="<div><label><input id='box' onClick='remove(this)' type='checkbox' />" + data[i] +
"</label></div>";
}
}
function remove(that) {
var check = that.parentElement.textContent;
//that.remove() if you need remove clicked box
for ( var i in list) {
if (list[i] == check) {
list.splice(list.indexOf(check),1);
}
}
console.log(list)
}
<input type="text" id="field" placeholder="Type name" />
<button type="submit" onclick="insertitem()">Submit</button>
<p id="para"></p>
var list = [];
var input;
function insertitem() {
input = document.getElementById('field').value;
list.push(input);
DisplayItem(list);
document.getElementById('field').value='';
}
function DisplayItem(data) {
var contain = document.getElementById('para');
contain.innerHTML='';
for ( var i in data) {
contain.innerHTML +="<div id='remove" + i + "'><label for='box" + i + "'><input id='box" + i + "' onClick='remove(" + i + ")' type='checkbox' />" + data[i] + "</label></div>";
}
}
function remove(targetId) {
var check = document.getElementById('box' + targetId).checked;
if(check){
console.log('Remove box' + targetId);
document.getElementById('remove' + targetId).innerHTML='';
}
}
<input type="text" id="field" placeholder="Type name" />
<button type="submit" onclick="insertitem()">Submit</button>
<p id="para"></p>
I just modified your JavaScript to pass an ID with a number to set each label apart from each other..

Jquery custom filters in HTML

I want create a custom filters using jquery.
I started here
var filters = {};
var data = [];
var filters = {};
filters.id = 0;
filters.title = "Users";
data[0] = filters;
var filters = {};
filters.id = 1;
filters.title = "Title";
data[1] = filters;
var filters = {};
filters.id = 2;
filters.title = "Start date";
data[2] = filters;
var filters = {};
filters.id = 3;
filters.title = "End date";
data[3] = filters;
var filters = {};
filters.id = 4;
filters.title = "Price";
data[4] = filters;
var filters = {};
filters.id = 5;
filters.title = "Category";
data[5] = filters;
var i = 0;
$.each(data, function(index, value) {
if (i < 2) {
$(".chooseFilter").append("<option data-filter-id=" + value.id + ">" + value.title + "</option>");
} else {
$(".chooseFilter").append("<option data-filter-id=" + value.id + " disabled>" + value.title + "</option>");
}
i++;
});
var dataHTMLFilters = [];
dataHTMLFilters[0] = '<input class="user" data-filterid="0" type="text" placeholder="Enter username">';
dataHTMLFilters[1] = '<input class="user" data-filterid="1" type="text" placeholder="Enter title">';
dataHTMLFilters[2] = '<input class="user" data-filterid="2" type="text" placeholder="Enter start date">';
dataHTMLFilters[3] = '<input class="user" data-filterid="3" type="text" placeholder="Enter end date">';
dataHTMLFilters[4] = '<input class="user" data-filterid="4" type="text" placeholder="Enter price">';
dataHTMLFilters[5] = '<input class="user" data-filterid="5" type="text" placeholder="Enter category">';
var limits = [];
limits[0] = 5;
limits[1] = 1;
limits[2] = 2;
limits[3] = 3;
limits[4] = 4;
limits[5] = 5;
$("body").on("change", ".chooseFilter", function() {
var filterId = $(this).find(":selected").attr("data-filter-id");
$(this).parent().prev().html(dataHTMLFilters[filterId]);
});
var buttons = '<div><button class="add">add</button><button class="remove">remove</button></div>';
$("body").on("click", ".add", function(e) {
e.preventDefault();
var filterID = $(this).parent().prev().find("option:selected").attr("data-filter-id");
$(".filters").append("<div class='filter'><div>" + $(".chooseFilter")[0].outerHTML + '</div>' + buttons + "</div>");
$(".filter").last().prepend("<div class='sibling'>" + dataHTMLFilters[$(".filter:last-child .chooseFilter option:not(:disabled)").attr("data-filter-id")] + "</div>");
if ($(".chooseFilter option[data-filter-id=" + filterID + "]:selected").length >= limits[filterID]) {
$(".chooseFilter option[data-filter-id=" + filterID + "]").prop("disabled", true);
var filterIdSelected = $(".chooseFilter option:not(:disabled)").first().attr("data-filter-id");
$(".chooseFilter").last().find("option[data-filter-id=" + filterIdSelected + "]").attr("selected", true);
console.log(dataHTMLFilters[filterIdSelected]);
$(".chooseFilter").last().parent().prev().html(dataHTMLFilters[filterIdSelected]);
}
});
$("body").on("click", ".remove", function(e) {
e.preventDefault();
$(this).parent().parent().remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="filters">
<div class="filter">
<div class="sibling">
<input class="user" data-filterid="0" type="text" placeholder="Enter username">
</div>
<div>
<select class="chooseFilter" style="width: 100%;">
</select>
</div>
<div>
<button class="add ">add</button>
</div>
</div>
</div>
Filters must fulfill,comatibile with:
Take limits to attention in add, remove and change. If limit is equal to instance of length in HTML document filter must be disabled
Basic filters are users, title when filters is only one this two option must be not disabled rest must be disabled when event is add, remove or change
Any ideas how I could do that? I try various method but result always are the same , filters is not compatibile.
If you want some more information how it should work just say.
I see it like this when add,remove and change:
if(users.length >= limit){
//set all option in select where filter is user to disabled = true
}
if(title.length >= limit){
//set all option in select where filter is title to disabled = true
}
if(filters.length > 1){
//options in select set to disable=false
}
if(filters.length < 1){
//options in select set to disable=true and title, users set to false
}

How to get the values of all textfields in add/remove textfields and form JSON

I'm using a plugin to duplicate textfields on add and remove buttons. Now, after getting the fields added and removed, I want to form JSON out of all the textfields and POST it on submit.
Below is the code -
$(function () {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').live('click', function () {
$('<p><label for="p_scnts"><input type="text" id="p_scnt_' + i + '" size="20" name="p_scnt_' + i + '" value="" placeholder="Input Value" /></label> Remove</p>').appendTo(scntDiv);
i++;
return false;
});
$('#remScnt').live('click', function () {
if (i > 2) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
JSFiddle can be referred to.
I want to get the values of all textfields and form JSON.
Iterate through the input fields, grab their values, and push them through JSON.stringify to create your desired JSON.
function serializeAndPost() {
var values = [];
$( '#p_scents input[id^=p_scnt_]' ).each( function ( index, element ) {
values.push( element.value );
} );
var json = JSON.stringify( { "welcomesList": values } );
// Do your POSTing here
}
Updated fiddle:
https://jsfiddle.net/tZPg4/11019/
I don't know if this is the best solution as I am building a string rather than an JSON object but here is my solution:
HTML
<input type="button" id="btnSubmit" value="Submit"></input>
JS:
$(function () {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').live('click', function () {
$('<p><label for="p_scnts"><input type="text" id="p_scnt_' + i + '" size="20" name="p_scnt_' + i + '" value="" placeholder="Input Value" /></label> Remove</p>').appendTo(scntDiv);
i++;
return false;
});
$('#remScnt').live('click', function () {
if (i > 2) {
$(this).parents('p').remove();
i--;
}
return false;
});
$('#btnSubmit').click(function(e) {
e.preventDefault();
var str = [];
$.each($('input[type=text]'), function(i, val) {
var el = $(this);
str.push('"' + el.attr("id") + '":"' + el.val() +'"');
});
var json_string = "{" + str + "}";
});
});

Categories

Resources