jQuery: Get related or nearly elements? - javascript

My codes in HTML:
<p><input type="text" class="txt" id="u" /><label for="u">user</label></p>
<p><input type="text" class="txt" id="p" /><label for="p">pass</label></p>
Javascript:
$(document).ready(function() {
if( $('.txt').val() ) {
//change st in related label tag
}
});
How to do that? Please help me solve this issue. Thank you very much !

You can do:
$("input.txt").focus() {
$("label[for='" + this.id + "']").addClass("highlight");
}).blur(function() {
$("label[for='" + this.id + "']").removeClass("highlight");
});
with:
label.highlight { background: yellow; font-weight: bold; }
While an input field has focus, its label (assuming it has one) is highlighted.
Edit: To traverse the inputs and do something with the labels:
$(":input[id]").each(function() {
if ($(this).val() != '') {
$("label[for='" + this.id + "'").each(do_something);
}
});
function do_something() {
// this refers to the label
}
or simply:
$(":input[id]").each(function() {
if ($(this).val() != '') {
$("label[for='" + this.id + "'").addClass("notnull");
}
});
or you can go the other way:
$("label[for]").each(function() {
var label = this;
$("#" + $(this).attr("foo") + ":input").each(function() {
if ($(this).val() != "") {
$(label).addClass("notnull");
}
});
});

You can look for the labels first and find related text fields, like so:
$('label[for]').each (function ()
{
var label = $(this), textfield = $('#' + label.attr('for') + '.txt');
if (textfield.length && textfield.val ())
doSomething (label);
});

Related

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.

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 + "}";
});
});

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

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;
});
};

how to show hidden button if more than 1 checkbox selected

I have 2 buttons add and group. Initially group button is hidden. Add button is used for creating records.
So for example:
When 5 records are created(pressing 5 times add button). Now if user selects more than
checkbox, then the hidden group button should appear. Can any body please tell me how to do this?
Please see this fiddle
I am using bootstrap css and for hiding I do as
<input type="button" id="btn2" class="btn btn-lg btn-primary hide" value="Group">
UPDATE
Check boxes will only appear if user enters some records. Filling the form and after pressing the add button
See this FIDDLE
$(document).on('change','#mytable input:checkbox',function () {
if($('#mytable input:checkbox:checked').length > 1) {
$('#btn2').removeClass('hide')
}
else {
$('#btn2').addClass('hide')
}
});
Here's the FIDDLE
if($('#mytable input:checkbox:checked').length > 1)
$('#btn2').show();
else
$('#btn2').hide();
Add a check in the change event for the checkboxes. fiddle and example below:
$(document).on('change','#mytable input:checkbox',function () {
if(!this.checked)
{
key=$(this).attr('name').replace('mytr','');
alert(key);
obj[key]=null;
}
//updated using your bootstrap class to show/hide
if($('#mytable input:checkbox:checked').length > 1) {
$('#btn2').removeClass('hide');
} else {
$('#btn2').addClass('hide');
}
});
Updated to use bootstrap class as per your updated question.
Try This
var val = 0;
var groupTrCount = 0;
$(document).ready(function () {
var obj={};
$('#btn1').click(function () {
if ($(".span4").val() != "") {
$("#mytable").append('<tr id="mytr' + val + '"></tr>');
$tr=$("#mytr" + val);
$tr.append('<td class=\"cb\"><input type=\"checkbox\" value=\"yes\" name="mytr' + val + '" unchecked ></td>');
$(".span4").each(function () {
$tr.append("<td >" + $(this).val() + "</td>");
});
var arr={};
name=($tr.find('td:eq(1)').text());
email=($tr.find('td:eq(2)').text());
mobile=($tr.find('td:eq(3)').text());
arr['name']=name;arr['email']=email;arr['mobile']=mobile;
obj[val]=arr;
val++;
} else {
alert("please fill the form completely");
}
});
$(document).on('click', '#btn2',function () {
var creat_group = confirm("Do you want to creat a group??");
if (creat_group) {
console.log(obj);
$tr.append("<td >" + groupTrCount + "</td>");
$("#groupsTable").append('<tr id="groupTr' + groupTrCount + '"></tr>');
$tr=$("#groupTr" + groupTrCount);
$tr.append("<td >Group:" + groupTrCount + "</td>"); // or you can use whatever name you want in place of "Group:"
var userColumn = "<ul>";
$('#mytable tr').filter(':has(:checkbox:checked)').each(function() {
var count=0;
$(this).find('td').each(function() {
if(count == 1){
userColumn+= "<li>" + $(this).html() + "</li>" ;
}
count++;
});
});;
userColumn+="<ul>";
$tr.append("<td >" +userColumn+ "</td>");
groupTrCount++;
}
});
$(document).on('change','#mytable input:checkbox',function () {
var rowCount = $('#mytable tr').length;
if($('input:checkbox:checked').length > 1 && rowcount > 6) {
$('#btn2').removeClass('hide')
}
});
});
Updted Fiddle is : http://jsfiddle.net/4GP9c/184/

How to only clear file upload field?

Here is the JSfiddle: http://jsfiddle.net/buyC9/128/
I want to clear only the file upload field when pressed on clear.
My HTML:
<h1>Upload image:</h1>
<input type="file" name="blog[opload]" id="blog_opload" class="imagec">
<input type="url" size="50" name="blog[url]" id="blog_url" class="imagec">
<div id="preview">
</div>
My Jquery:
$('input').change(function() {
var el = $(this);
if (this.value === "") {
$('.imagec').prop('disabled', false);
this.disabled = false;
$('#preview').hide();
} else {
$('.imagec').prop('disabled', true);
el.prop('disabled', false);
alert(el.val());
if (el.attr('type') == 'url') {
$('#preview').show().html('<img src=' + '"' + el.val() + '"' + ' />');
}
}
});
function reset_html(id) {
$('.' + id).html( $('.' + id).html() );
}
var imagec_index = 0;
$('input[type=file]').each(function() {
imagec_index++;
$(this).wrap('<div id="imagec_' + imagec_index + '"></div>');
$(this).after('<input type="button" value="Clear" onclick="reset_html(\'imagec_' + imagec_index + '\')" />');
});
How about:
$('input[value="Clear"]').click(function(){
$('#blog_opload').val('');
});
Example: jsFiddle
You could also get rid of onclick="reset_html(\'imagec_' + imagec_index + '\')" if you use this.
Quick answer is replace it:
$("#clear").click(function(event){
event.preventDefault();
$("#control").replaceWith("<input type='file' id='control' />");
});
<input type="file" id="control" />
Clear
You can do simply
$("#filuploadId")[0].value = "";
In your code you meant to use the ID selector but instead are using class selector.
$('.' + id).html( $('.' + id).html() );
should be
$('#' + id).html( $('#' + id).html() );
Updated jsFiddle

Categories

Resources