Fill inputs by clicking on div - jQuery - javascript

I wanna fill a form automatically by clicking on a div which has all the contents required for the form.
My div -
<div class="ab">
<ul>
<li>Sahar Raj</li>
<li>Address.</li>
<li>City</li>
<li>State</li>
<li>Pin</li>
<li>9876543210</li>
</ul>
</div>
Form -
<input class="required" type="text" name="name" />
<textarea name="address" class="required"></textarea>
<input class="required" type="text" name="city" />
<select name="state">
<option value="0">State1</option>
<option value="1">State2</option>
</select>
<input class="required" type="text" name="pin" />
<input class="required" type="text" name="phone" />
Any idea how to achieve this? Thanks

Try this:
$(document).ready(function () {
$(".ab").on("click", function () {
$(".ab ul >li").each(function (x, value) {
var text = $(this).html();
var dom = $("input,textarea,select").get(x);
$(dom).val(text);
});
})
});
JSFIDDLE DEMO

You can use a mix of map and each methods to get it working.
Remember that the order is important to get it working. If you have haphazard order, you can use the data-* attributes to store the related field info and then populate it.
$(function () {
$('div.ab').click(function() {
var data = $('.ab li').map(function () {
return this.innerHTML;
// or return $(this).text();
}).get();
$('input').each(function (i) {
this.value = data[i];
// or $(this).val(data[i]);
});
});
});
Check Fiddle
UPDATE
I have used data-* attributes to establish a relationship between the elements as they are no more of the same kind. This will be mapped to the name attribute of the field. Also encased the fields in a container as that makes them easier to select.
HTML
<div class="ab">
<ul>
<li data-key="name">Sahar Raj</li>
<li data-key="address">Address.</li>
<li data-key="city">City</li>
<li data-key="state">State2</li>
<li data-key="pin">Pin</li>
<li data-key="phone">9876543210</li>
</ul>
</div>
<div class="container">
<input class="required" type="text" name="name" />
<textarea name="address" class="required"></textarea>
<input class="required" type="text" name="city" />
<select name="state">
<option value="0">State1</option>
<option value="1">State2</option>
</select>
<input class="required" type="text" name="pin" />
<input class="required" type="text" name="phone" />
</div>
JS
$(function () {
$('div.ab').click(function () {
$('.container').children().each(function() {
// Get the corresponding key value from li.
var $this = $(this),
key = $this.attr('name');
// Find the li with that key
var txt = $('.ab li[data-key="'+ key +'"]').text();
$this.val(txt);
});
});
});
Check Data Fiddle

I'm guessing your inputs are all in a form and that the ul is always in the right order.
If that is true you can use:
$(function(){
$('div.ab').on('click',function(){
$('form input').each(function(index){
$(this).val($('div.ab ul li:eq(' + index + ')').html());
});
});
});

You can add id for every <li> and bind the click, for example the name:
HTML:
<li id="name">Sahar Raj</li>
jQuery:
$('.ab').on('click', function(){
$('input[name="name"]').val($('#name').html());
});

var counter = 0;
$("#clickme").click(function() {
$("#list li").each(function() {
var text = $(this).text();
$("input:eq(" + counter + ")").val(text);
counter++;
});
});
http://jsfiddle.net/PgYjH/1/

You can use this
$('div ul li').click(function () {
var divIndex = $(this).index();
var divText = $(this).text();
$('input').each(function () {
if ($(this).index() == divIndex) {
$(this).prop('value', divText);
}
});
});
On the click of one <li> it will read its index position and take its value/text. Then look for the <input> with same index and give the value/text to it.
The best would be to have data- attributes on both input and li, to avoid problems if you mix up the order how they are.
DEMO HERE

Related

Refactoring keyup function

I'm trying to make a form previewer.
The idea is to make a layer that shows user info printed on a div by default, but with the possibility of modifying their data in real time and show it in the box.
My code works, but I don't know how to simplify it.
Here's my code:
function preview() {
$('#previewName').html($('#Name').val());
$('#Name').keyup(function () {
$('#previewName').html($(this).val());
});
$('#previewDirection').html($('#Direction').val());
$('#Direction').keyup(function () {
$('#previewDirection').html($(this).val());
});
$('#previewPostal').html($('#Postal').val());
$('#Postal').keyup(function () {
$('#previewPostal').html($(this).val());
});
$('#previewCountry').html($('#Country option:selected').text());
$('#Country option:selected').change(function () {
$('#previewCountry').text($(this).text());
});
}
<form id="form">
<div>
<div>
<label>Name</label>
<input type="text" id="Name" name="Name" value="">
</div>
<div>
<label>Direction</label>
<input type="text" id="Direction" name="Direction">
</div>
<div>
<label>Postal</label>
<input type="text" id="Postal" name="Postal">
</div>
<div>
<label>Country</label>
<div>
<select name="Country" id="Country">
<option value="">x</option>
<option value="">y</option>
</select>
</div>
</div>
</div>
<div>
<div class="box">
<p class="strong" id="previewName"></p>
<p class="mb0" id="previewDirection"></p>
<p id="previewPostal"></p>
<p id="previewCountry"></p>
</div>
</div>
</form>
Any idea?
You can simplify this by querying the form input elements and using the id and value to update the preview.
// cache form selector
var form = $('#form');
// cache all form input elements
var inputs = form.find('input');
// cache all form select elements
var selects = form.find('select');
inputs.keyup(function(){
var id = this.id,
value = this.value;
$('#preview' + id).html(value);
});
selects.change(function(){
var id = this.id,
option = $(this).find('option:selected'),
value = option.val();
$('#preview' + id).html(value);
});
or a condensed version
$('#form input').keyup(function(){
var id = this.id,
value = this.value;
$('#preview' + id).html(value);
});
$('#form select').change(function(){
var id = this.id,
option = $(this).find('option:selected'),
value = option.val();
$('#preview' + id).html(value);
});
Demo

Make jQuery dynamic fields unique

I have fields in form which I add dynamically. How can I check if values of these fields unique?
HTML:
<div class="inputs">
<input type="text" class="form-control" id="regSection" name="regSection[]" required="required">
</div>
ADD
JavaScript:
$('#add').click(function(e) {
e.preventDefault();
$('<input type="text" class="form-control" id="regSection" name="regSection[]">').fadeIn('slow').appendTo('.inputs');
});
I've removed the id from the input as ID's must be unique.
This code will return found id the values in textbox repeat. Otherwise, it will return not found.
$('#add').click(function(e) {
e.preventDefault();
$('<input type="text" class="form-control" n ame="regSection[]">').appendTo('.inputs');
});
$('#check').click(function(e){
var arr = [];
var found = 0;
$('.inputs input').each(function(){
var myVal = $(this).val();
if(arr.includes(myVal))
found++;
else
arr.push(myVal);
});
if(found)
console.log('found');
else
console.log('unique');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inputs">
<input type="text" class="form-control" name="regSection[]" required="required">
</div>
ADD
<button id="check">Check</button>

How to multiple filter list using jquery/javascript

I have a html where I can filter based on their data but I don't know how to combine it.
This is my script and the search name is working already but the radio button isActive still not working and need to add on my filter. I don't know how to and it on filter.
$('input[type=text][name=search_name').on('input', function(e) {
e.stopPropagation();
e.preventDefault();
var fullname = $(this).val();
var isActive = $('input[type=radio][name=isActive]').val();
searchStudent(fullname, isActive);
});
$('input[type=radio][name=isActive]').on('change', function(e) {
e.stopPropagation();
e.preventDefault();
var fullname = $('input[type=text][name=search_name').val();
var isActive = $(this).val();
searchStudent(fullname, isActive);
});
function searchStudent(fullname, isActive) {
$("ul li").each(function() {
// I don't know how to add the isActive
if ($(this).data('fullname').search(new RegExp(fullname, "i")) < 0) {
$(this).hide();
} else {
$(this).show();
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" name="search_name">
<span><input type="radio" checked="" autocomplete="off" value="2" name="isActive"> All</span>
<span><input type="radio" autocomplete="off" value="1" name="isActive"> Active</span>
<span><input type="radio" autocomplete="off" value="0" name="isActive"> Inactive</span>
</div>
<ul>
<li data-fullname="Jerald Patalinghug" data-firstname="Jerald" data-lastname="Patalinghug" data-isActive="1">Jerald Patalinghug</li>
<li data-fullname="Eldrin Gok-ong" data-firstname="Eldrin" data-lastname="Gok-ong" data-isActive="1">Eldrin Gok-ong</li>
<li data-fullname="Uelmar Ortega" data-firstname="Uelmar" data-lastname="Ortega" data-isActive="0">Uelmar Ortega</li>
</ul>
so when I choose all = 2, then I will see all people, active = 1 I will see the active, then inActive = 0 to see the inactive people.
I would suggest using a single update function that you call when both the inputs or the textField change.
In this update function, you would query the selected checkbox and the text field.
Other solutions would imply recording the selected values or pre-selecting the relevant elements to avoid querying the DOM each time, but in my opinion, it is not worth it.
$('input[type=text][name=search_name').on('input', updateFilter);
$('input[type=radio][name=isActive]').on('change', updateFilter);
function updateFilter(){
var fullname = $('input[type=text][name=search_name').val();
var isActive = $('input[type=radio][name=isActive]:checked').val();
searchStudent(fullname, +isActive);
}
function searchStudent(fullname, isActive) {
$("ul li").each(function() {
if ($(this).data('fullname').search(new RegExp(fullname, "i")) < 0
|| isActive !== 2 && +$(this).data('isactive') !== isActive) {
$(this).hide();
} else {
$(this).show();
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" name="search_name">
<span><input type="radio" checked="true" autocomplete="off" value="2" name="isActive"> All</span>
<span><input type="radio" autocomplete="off" value="1" name="isActive"> Active</span>
<span><input type="radio" autocomplete="off" value="0" name="isActive"> Inactive</span>
</div>
<ul>
<li data-fullname="Jerald Patalinghug" data-firstname="Jerald" data-lastname="Patalinghug" data-isActive="1">Jerald Patalinghug</li>
<li data-fullname="Eldrin Gok-ong" data-firstname="Eldrin" data-lastname="Gok-ong" data-isActive="1">Eldrin Gok-ong</li>
<li data-fullname="Uelmar Ortega" data-firstname="Uelmar" data-lastname="Ortega" data-isActive="0">Uelmar Ortega</li>
</ul>
Change your jQuery selector to exclude the data-isActive attributes you don't want:
$("ul li:not([data-isActive='0'])").each(function () {
...
}
Just add a check in the current if-statement. I did refactor your code a bit, since I was having some issues myself. This was mostly because my IDE was annoying me ...
But the snippet works and I hope it'll help you out.
$("input[name='search_name']").on("input", function() {
var fullname = $(this).val();
var isActive = $("input[type='radio'][name='isActive']:checked").val();
searchStudent(fullname, isActive);
//If input is empty, just trigger the checked radiobutton
if(fullname === "")
$("input[type='radio'][name='isActive']:checked").change();
});
$("input[name='isActive']").change(function() {
var fullname = $("input[name='search_name']").val();
var isActive = $(this).val();
searchStudent(fullname, isActive);
})
function searchStudent(pFullName, pIsActive)
{
$("ul li").each(function() {
var element = $(this);
var isActive = element.attr("data-isActive");
if((element.data("fullname").search(new RegExp(pFullName, "i")) >= 0) && parseInt(isActive) === parseInt(pIsActive))
element.show();
else
element.hide();
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="search_name">
<span><input type="radio" checked="" autocomplete="off" value="2" name="isActive"> All</span>
<span><input type="radio" autocomplete="off" value="1" name="isActive"> Active</span>
<span><input type="radio" autocomplete="off" value="0" name="isActive"> Inactive</span>
<ul>
<li data-fullname="Jerald Patalinghug" data-firstname="Jerald" data-lastname="Patalinghug" data-isActive="1">Jerald Patalinghug</li>
<li data-fullname="Eldrin Gok-ong" data-firstname="Eldrin" data-lastname="Gok-ong" data-isActive="1">Eldrin Gok-ong</li>
<li data-fullname="Uelmar Ortega" data-firstname="Uelmar" data-lastname="Ortega" data-isActive="0">Uelmar Ortega</li>
</ul>

Close option when other is opened

I have such html code printed with echo :
<input id="58" readonly="readonly" class="cell_to_edit" value="Accepted">
<span id="58" class="toggle_status">
<select class="status_change">
<option>Accepted</option>
<option>Waiting</option>
<option>Canceled</option>
</select>
</span>
<input id="59" readonly="readonly" class="cell_to_edit" value="Canceled">
<span id="59" class="toggle_status">
<select class="status_change">
<option>Accepted</option>
<option>Waiting</option>
<option>Canceled</option>
</select>
</span>
Jquery :
$(function() {
$('.cell_to_edit').on('click', function () {
var inputID = $(this).attr('id');
$(this).hide();
$("span[id=" + inputID + "]").show();
$("span[id=" + inputID + "]").attr("id",""+inputID+"");
$(".status_change").change(function() {
var selectIDforAjax = "id="+inputID;
console.log(selectIDforAjax);
$(this).hide();
$("input[id=" + inputID + "]").show();
});
});
});
I have such problem, when I open the selected options and hide input everything is messed up. How to close the option when the second one is opened? Because in future I'll pass the ID to php with Ajax to make the changes in database.
There is no need to have the id in your case(if the structure of your html is the same as given here). The elements you want to target(input.cell_to_edit and .toggle_status) are next/prev sibling elements so use that relationship instead of using ID to target them.
$(function() {
$('.cell_to_edit').on('click', function() {
$(this).hide().next().show();
});
$(".status_change").change(function() {
var $span = $(this).parent();
$span.hide().prev().show();
var id = $span.data('id');
alert(id)
});
});
.toggle_status {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input readonly="readonly" class="cell_to_edit" value="Accepted" />
<span data-id="58" class="toggle_status">
<select class="status_change">
<option>Accepted</option>
<option>Waiting</option>
<option>Canceled</option>
</select>
</span>
<input readonly="readonly" class="cell_to_edit" value="Canceled" />
<span data-id="59" class="toggle_status">
<select class="status_change">
<option>Accepted</option>
<option>Waiting</option>
<option>Canceled</option>
</select>
</span>

Not working select option dynamic field in jquery

jQuery(function() {
var currentCount = 0;
jQuery('#addMoreEmail').click(function() {
currentCount = cloning('#MoreEmailDetails', '#MoreEmails', currentCount);
return false;
});
function cloning(from, to, counter) {
var clone = $(from).clone();
//console.log(clone);
counter++;
// Replace the input attributes:
clone.find(':input').each(function() {
var name = jQuery(this).attr('name').replace(0, counter);
var id = jQuery(this).attr('id').replace(0, counter);
jQuery(this).attr({
'name': name,
'id': id
}).val();
});
// Replace the label for attribute:
clone.find('label').each(function() {
var newFor = jQuery(this).attr('for').replace(0, counter);
jQuery(this).attr('for', newFor);
});
// Replace the text between html tags:
clone = clone.html().replace(1, counter);
jQuery(to).before(clone);
return counter;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="MoreEmailDetails">
<div class="form-group users">
<input type="text" required="required" id="LeadEmailDetail0FirstName" value="" name="data[LeadEmailDetail][0][first_name]">
<label for="LeadEmailDetail0FirstName">First Name</label>
<input type="text" id="LeadEmailDetail0LastName" value="" name="data[LeadEmailDetail][0][last_name]">
<label for="LeadEmailDetail0FirstName">First Name</label>
<select id="LeadEmailDetail0CountryId" class="select-replace select2-offscreen" name="data[LeadEmailDetail][0][country_id]" tabindex="-1" title="Country">
<option value="">Choose a country</option>
<option value="2">SOUTHEASTERN EUROPE</option>
</select>
<label for="LeadEmailDetail0CountryId">Country</label>
<input type="checkbox" id="LeadEmailDetail0PrimaryEmail" value="1" name="data[LeadEmailDetail][0][primary_email]">
<label for="LeadEmailDetail0PrimaryEmail">Primary Email</label>
</div ">
</div">
<div id="MoreEmails"></div>
<input type="submit" value="Add More" id="addMoreEmail">
In above code input type text and checkbox working fine (adding dynamic fields after click add more) but i m getting below error in case select option
TypeError: jQuery(...).attr(...) is undefined
You need to add a null check for jQuery(this).attr('name')) . JSFIDDLE
Following is the modified JS code block.
clone.find(':input').each(function() {
if(jQuery(this).attr('name')) {
var name = jQuery(this).attr('name').replace(0, counter);
var id = jQuery(this).attr('id').replace(0, counter);
jQuery(this).attr({
'name': name,
'id': id
}).val(); }
});

Categories

Resources