How to set minimum length of 6 in input? [Live seach] - javascript

How can I display the results with at least two characters? So I'll get faster results list.
I can not use any Submit button, this is auto complete form
HTML :
<input class="form-control btn-group-lg" data-minlength="2" type="text" id="autoCompleteSearch" value="" required="required">
JavaScript:
$(document).ready(function () {
var data = [
"id": "",
"soruCore": "",
"soruIceri": "",
"sik1": ""
},
];
$('#txt-search').keyup(function () {
var searchField = $(this).val();
if (searchField === '') {
$('#filter-records').html('');
return;
}
var regex = new RegExp(searchField, "i");
var output = '<div class="row" style="margin: 10px;">';
var count = 1;
$.each(data, function (key, val) {
if ((val.soruIceri.search(regex) != -1) || (val.soruCore.search(regex) != -1)) {
output += '<div class="container">';
output += '<div class="row">';
output += '<h2 style="color: #FFFFFF">' + val.sik1 + '</h2>';
output += '</div></div>';
output += '</section>';
if (count % 2 == 0) {
output += '</div><div class="row">';
}
count++;
}
});
output += '</div>';
$('#filter-records').html(output);
});
});

Try this:
function checkLength(){
var textbox = document.getElementById("textbox");
if(textbox.value.length >= 6)
}

You should use the pattern attribute. You might need the "required" attribute too because otherwise an empty value will be excluded from constraint validation.
<input required pattern=".{6,}" title="6 characters minimum">
<input required pattern=".{6,20}" title="6 to 20 characters">

Related

jQuery shows "undefined" for values after unchecking checkbox

I am new to jQuery and AJAX and I was trying to set up a script that displays a MySQL table which can be updated. I included a checkbox to update various entries at the same time. It works fine but if I uncheck the checkbox, all values change to "undefined".
Here is my code:
$(document).ready(function(){
function fetch_data()
{
$.ajax({
url:"select.php",
method:"POST",
dataType:"json",
success:function(data)
{
var html = '';
for(var count = 0; count < data.length; count++)
{
var bezahlstatus = data[count].bezahlstatus;
var guest_amount = data[count].guest_amount;
html += '<tr>';
html += '<td><input type="checkbox" id="'+data[count].id+'" data-email="'+data[count].email+'" data-guest_amount="'+data[count].guest_amount+'" data-date_reservation="'+data[count].date_reservation+'" data-menu_own="'+data[count].menu_own+'" data-bezahlstatus="'+data[count].bezahlstatus+'" class="check_box"></td>';
html += '<td>'+data[count].email+'</td>';
html += (guest_amount == "") ? "<td>0</td>" : "<td>"+guest_amount+"</td>";
html += '<td>'+data[count].date_reservation+'</td>';
html += '<td>'+data[count].menu_own+'</td>';
html += (bezahlstatus == null || bezahlstatus == "") ? "<td>nicht bezahlt</td>" : "<td>"+data[count].bezahlstatus+"</td>";
}
$('tbody').html(html);
}
});
}
fetch_data();
$(document).on('click', '.check_box', function() {
var html = '';
var guest_amount = $(this).data('guest_amount');
var bezahlstatus = $(this).data('bezahlstatus');
if(this.checked)
{
html = '<td><input type="checkbox" id="'+$(this).attr('id')+'" data-email="'+$(this).attr('email')+'" data-guest_amount="'+$(this).attr('guest_amount')+'" data-date_reservation="'+$(this).attr('date_reservation')+'" data-menu_own="'+$(this).attr('menu_own')+'" data-bezahlstatus="'+$(this).attr('bezahlstatus')+'" class="check_box" checked></td>';
html += '<td><input type="text" name="email[]" class="form-control" value="'+$(this).data("email")+'" /></td>';
html += (guest_amount == "") ? '<td>0</td>' : '<td>'+guest_amount+'</td>';
html += '<td>'+$(this).data('date_reservation')+'</td>';
html += '<td><select name="menu_own[]" id="menu_own_'+$(this).attr('id')+'" class="form-control"><option value="Hauptmenü 1">Hauptmenü 1</option><option value="Hauptmenü 2">Hauptmenü 2</option><option value="Hauptmenü 3">Hauptmenü 3</option></select></td>';
html += '<td><select name="bezahlstatus[]" id="bezahlstatus_'+$(this).attr('id')+'" class="form-control"><option value="">nicht bezahlt</option><option value="bezahlt">bezahlt</option></select></td><input type="hidden" name="hidden_id[]" value="'+$(this).attr('id')+'" />';
}
else
{
html = '<td><input type="checkbox" id="'+$(this).attr('id')+'" data-email="'+$(this).attr('email')+'" data-guest_amount="'+$(this).attr('guest_amount')+'" data-date_reservation="'+$(this).attr('date_reservation')+'" data-menu_own="'+$(this).attr('menu_own')+'" data-bezahlstatus="'+$(this).attr('bezahlstatus')+'" class="check_box"></td>';
html += '<td>'+$(this).data('email')+'</td>';
html += (guest_amount == "") ? '<td>0</td>' : '<td>'+guest_amount+'</td>';
html += '<td>'+$(this).data('date_reservation')+'</td>';
html += '<td>'+$(this).data('menu_own')+'</td>';
html += (bezahlstatus == null || bezahlstatus == "") ? '<td>nicht bezahlt</td>' :
'<td>'+bezahlstatus+'</td>';
}
$(this).closest('tr').html(html);
$('#menu_own_'+$(this).attr('id')+'').val($(this).data('menu_own'));
$('#bezahlstatus_'+$(this).attr('id')+'').val($(this).data('bezahlstatus'));
});
$('#update_form').on('submit', function(event){
event.preventDefault();
if($('.check_box:checked').length > 0)
{
$.ajax({
url:"update.php",
method:"POST",
data:$(this).serialize(),
success:function()
{
alert('Der Eintrag wurde erfolgreich aktualisiert.');
fetch_data();
}
});
}
});
});
I tried to find the mistake in the code section where the checkbox is checked but I am unable to find it. Could someone please help me?
Thank you in advance!

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.

dynamic id selector not being called or instantiate

I am creating a jquery function, when I add new <tr id="select_row"> this tag with id will increase by one for example select_row1, select_row2, select_row3.
After the row has been increased I try to click on the checkbox but it does not trigger below as well as changing the value where id is #single_price0 and #total_price0
if ( ((meat_length == 1)&&(vege_length == 2)) || ((meat_length == 1)&&(vege_length == 1)) ) {};
var list = $('#add_order_table');
var initial = 0;
list.click(function(){
html = '<tr id="select-row'+initial+'">';
html += '<td class="col-md-7">';
//meat
html += '<div class="col-md-6">';
html += '<div class="checkbox"><label><input type="checkbox" name="meat'+initial+'[]" class="meat"> Black Pepper Fried Chicken</label></div>';
html += '<div class="checkbox"><label><input type="checkbox" name="meat'+initial+'[]" class="meat"> Pineapple Pork</label></div>';
html += '<div class="checkbox"><label><input type="checkbox" name="meat'+initial+'[]" class="meat"> Bitter Gourd with Dash Fish</label></div>';
html += '</div>';
//vege
html += '<div class="col-md-6">';
html += '<div class="checkbox"><label><input type="checkbox" name="vege'+initial+'[]" class="vege"> Garlic Bayam</label></div>';
html += '<div class="checkbox"><label><input type="checkbox" name="vege'+initial+'[]" class="vege"> Oyster Young Pakchoy</label></div>';
html += '</div>';
html += '</td>';
html += '<td class="col-md-1 text-center"><b><p>RM <span id="single_price'+initial+'">0.00</span></p><b></td>';
html += '<td class="col-md-2"><p><input id="qty'+initial+'"type="text" value="" name="demo" class="text-center qty_spinner"></p></td>';
html += '<td class="col-md-1 text-center"><b><p>RM <span id="total_price'+initial+'">0.00</span></p><b></td>';
html += '<td class="col-md-1 text-center"><p><button type="button" class="btn btn-danger" onclick="$(\'#select-row' + initial + '\').remove();">';
html += '<span class="glyphicon glyphicon-minus-sign" aria-hidden="true"></span>';
html += '</button></p></td>';
html += '</tr>';
$('#order_table tbody').append(html);
$('.qty_spinner').TouchSpin({
initval: 1,
min:1,
max:50,
buttondown_class: 'btn btn-danger',
buttonup_class: 'btn btn-primary',
});
var row = $("#select-row"+initial);
row.on('change',function(e){
var meat_length = $('input[class="meat"]:checked').length;
var vege_length = $('input[class="vege"]:checked').length;
if (meat_length == 0 || vege_length == 0) {
$("#single_price"+initial).text("0.00");
$("#total_price"+initial).text("0.00");
};
// 5.50 meal function
if ( ((meat_length == 1)&&(vege_length == 2)) || ((meat_length == 1)&&(vege_length == 1)) ) {
// set single price without parsing
$("#single_price"+initial).text("5.50");
//get single price with parsing
var single1 = parseFloat($("#single_price"+initial).text()).toFixed(2);
// get quantity value
var qty1 = parseInt($("#single_qty"+initial).val());
//single price multiply
var total = parseFloat(single1*qty1).toFixed(2);
$("#total_price"+initial).text(total);
};
// 6.00 meal function
if ( ((meat_length == 2)&&(vege_length == 1)) || (meat_length == 2) ) {
// set single price without parsing
$("#single_price"+initial).text("6.00");
//get single price with parsing
var single1 = parseFloat($("#single_price"+initial).text()).toFixed(2);
// get quantity value
var qty1 = parseInt($("#single_qty"+initial).val());
//single price multiply
var total = parseFloat(single1*qty1).toFixed(2);
$("#total_price"+initial).text(total);
};
});
initial++;
});
Wrap initial in a function, so it preserves the increment within the change function:
(function(initial) {
var row = $("#select-row"+initial);
row.on('change',function(e){
var meat_length = $('input[class="meat"]:checked').length;
var vege_length = $('input[class="vege"]:checked').length;
if (meat_length == 0 || vege_length == 0) {
$("#single_price"+initial).text("0.00");
$("#total_price"+initial).text("0.00");
};
// 5.50 meal function
if ( ((meat_length == 1)&&(vege_length == 2)) || ((meat_length == 1)&&(vege_length == 1)) ) {
// set single price without parsing
$("#single_price"+initial).text("5.50");
//get single price with parsing
var single1 = parseFloat($("#single_price"+initial).text()).toFixed(2);
// get quantity value
var qty1 = parseInt($("#single_qty"+initial).val());
//single price multiply
var total = parseFloat(single1*qty1).toFixed(2);
$("#total_price"+initial).text(total);
};
// 6.00 meal function
if ( ((meat_length == 2)&&(vege_length == 1)) || (meat_length == 2) ) {
// set single price without parsing
$("#single_price"+initial).text("6.00");
//get single price with parsing
var single1 = parseFloat($("#single_price"+initial).text()).toFixed(2);
// get quantity value
var qty1 = parseInt($("#single_qty"+initial).val());
//single price multiply
var total = parseFloat(single1*qty1).toFixed(2);
$("#total_price"+initial).text(total);
};
});
})(initial);

Iterating Ajax response and creating Dynamic table on some condition

I am trying to create a dynamic table with ajax response.
And want to put condition on check box like if item.statuscheck =1 will print checked Box with name and if item.statuscheck =0 unchecked box will display with same name.
i am able to display name dynamically. But problem is coming with check box.
Here is the code i am trying with. Please help me on this issue.
success(response)
{
$.each(response,function(index,item){
var status;
if(index >=0 and index <= 4)
{
if(item.statusCheck = 1)
{
status = <input type ="checked" checked/>
}
else{
status = <input type="checked" />
}
var content = '<td>'+ status + '</td>'
+<td>' + item.fieldName +'<td>';
$("#tableId").appent(content)
}
}
}
("#tableId").append(content)
Change appent to append
compare operator is == not = assign.Also careful 'and "
success(response)
{
$.each(response,function(index,item){
var status;
if(0 >= index <= 4)
{
if(item.statusCheck == 1)
{
status = '<input type ="checkbox" checked/>';
}
else{
status = '<input type="checkbox" />';
}
var content = '<td>'+ status + '</td>'
+'<td>' + item.fieldName +'<td>';
$("#tableId").append(content);
}
}
}
var content = item.statusCheck == 1 ? '<td><input type="checkbox" checked="checked" />'+item.fieldName+'</td>' : '<td><input type="checkbox" />'+item.fieldName+'</td>';
$("#tableId").append($(content));
Its not type = "checked" its type = "checkbox"
success(response)
{
$.each(response,function(index,item){
var status;
if(index >=0 and index <= 4)
{
if(item.statusCheck = 1)
{
status = <input type ="checkbox" checked/>
}
else{
status = <input type="checkbox"/>
}
var content = '<td>'+ status + '</td>'
+<td>' + item.fieldName +'<td>';
$("#tableId").appent(content)
}
}
}

Splitting an array

I have two javascript functions, the first one is working, teh second is working but not echoing the correct value in the hidden inputs.
Ive manage to get the last hidden input value correct but I'm not sure how
var customTicketsArr = Array();
function EditEventAddTicket(){
alertWrongTime = false;
var TicketName = jQuery("#ticketname").val();
var TicketPrice = jQuery("#ticketprice").val();
var ticketquantity = jQuery("#ticketquantity").val();
var storeString = "TicketName" + TicketName + "TicketPrice" + TicketPrice + "Quantity" + ticketquantity + '';
customTicketsArr.push(storeString);
EditEventUpdateTickets(true);
}
function EditEventUpdateTickets(fade){
jQuery("#custom_tickets_string").val(customTicketsArr);
var output = "";
var style = "";
for (i = customTicketsArr.length-1; i >= 0; i--){
ticketname = customTicketsArr[i].split("TicketName");
ticketprice = customTicketsArr[i].split("TicketPrice");
ticketquantity = customTicketsArr[i].split("Quantity");
if(fade){
if (customTicketsArr.length - 1 == i){
style = "display: none; ";
var fadeInDiv = i;
} else {
style = "";
}
}
if (i % 2 == 1) { style += "background-color: #660000; "}
html = "<div id='customticket" + i + "' class='customeventbase' style='" + style + "'>";
html += '<input type="hidden" name="customTicketid[' + i + '][Name]" id="customticketName' + i + '" value="'+ ticketname + '" />';
html += '<input type="hidden" name="customTicketid[' + i + '][Price]" id="customticketPrice' + i + '" value="' +ticketprice[1] +'" />';
html += '<input type="hidden" name="customTicketid[' + i + '][Quantity]" id="customticketQuantity' + i + '" value="'+ ticketquantity[1] +'" />';
html += '<button class="customeventdel" type="button" onClick="EditEventRemoveDate(' + i + ')"></button>';
html += '<div class="clear"></div>';
html += '</div>\n';
output += html;
}
output += "<input type='hidden' id='custom_ticket_info' name='custom_ticket_info' value='" + customTicketsArr + "' />";
jQuery("#custom_ticket_container").html(output);
if(fade){
setTimeout("EditEventfadeInDiv(" + fadeInDiv +")", 10);
}
}
this outputs:
<div style="background-color: #660000; " class="customeventbase" id="customticket1">
<input type="hidden" value=",testTicketPrice50Quantity44" id="customticketName1" name="customTicketid[1][Name]">
<input type="hidden" value="undefined" id="customticketPrice1" name="customTicketid[1][Price]">
<input type="hidden" value="44" id="customticketQuantity1" name="customTicketid[1][Quantity]">
<button onclick="EditEventRemoveDate(1)" type="button" class="customeventdel"></button>
<div class="clear"></div></div>
the values for the first two hidden fields are incorrect
They're not incorrect values - split() is doing exactly what it is supposed to - returning an array of substrings after removing the separator.
With your string structure, splitting on TicketName will give you two strings - the substring before the separator and the substring after - TicketName itself is not included.
Thus, for the string "TicketNametestTicketPrice50Quantity44", you will get "" and "testTicketPrice50Quantity44" when you split on "TicketName" . Splitting the same string on TicketPrice will give you "TicketNametest" and "50Quantity44".
I'd suggest putting objects into your array instead -
var storeObject = {
"TicketName" : TicketName,
"TicketPrice" : TicketPrice,
"Quantity" : ticketquantity
};
customTicketsArr.push(storeObject);
You can then get back the data as:
for (i = customTicketsArr.length-1; i >= 0; i--){
var currentObject = customTicketsArr[i];
var ticketname = currentObject.TicketName;
var ticketprice = currentObject.TicketPrice;
var ticketquantity = currentObject.Quantity;
//do other stuff here
}
why do you save it as a string? I would recommend storing it in an object:
function EditEventAddTicket(){
alertWrongTime = false;
var TicketName = jQuery("#ticketname").val();
var TicketPrice = jQuery("#ticketprice").val();
var ticketquantity = jQuery("#ticketquantity").val();
var ticket = {"TicketName": TicketName, "TicketPrice": TicketPrice, "Quantity": ticketquantity};
customTicketsArr.push(ticket);
EditEventUpdateTickets(true);
}
and then you can simply load the data:
for (i = customTicketsArr.length-1; i >= 0; i--){
ticketname = customTicketsArr[i].TicketName;
ticketprice = customTicketsArr[i].TicketPrice;
ticketquantity = customTicketsArr[i].Quantity;
// ...
}
Why not just make a two dimensional array?
var customTicketsArr = Array();
function EditEventAddTicket() {
customTicketsArr.push({
'name' : jQuery("#ticketname").val(),
'price' : jQuery("#ticketprice").val(),
'qty' : jQuery("#ticketquantity").val()
});
}

Categories

Resources