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
Related
I have a text input where user have to enter their surname and I want that surname as they enter it to appear below in a dropdown, using HTML and Javascript. This is my code so far but it does not work:
<form id= 'surnameReg'>
<label for='surname'>Surname:</label>
<input type='text' id="surname">
</form>
<form id='chooseSur'>
<label for="who">Who:</label>
<select id="who">
</select>
</form>
And my JS:
function drop() {
var surnArr=[];
var select = document.getElementById("who");
for(var i = 0; i <surnArr.length; i++) {
var sur= surnArr[i];
var op = document.createElement("option");
op.textContent = sur;
op.value = sur;
select.appendChild(op);
}
}
You can set an event listener on the first form on submit and then create and append the option as follows:
document.getElementById("surnameReg").addEventListener("submit",function(e){
e.preventDefault();
let surname = document.getElementById("surname").value;
if(surname){
var select = document.getElementById("who");
var op = document.createElement("option");
op.textContent = surname;
op.value = surname;
select.appendChild(op);
}
});
<form id= 'surnameReg' >
<label for='surname'>Surname:</label>
<input type='text' id="surname" >
</form>
<form id='chooseSur' >
<label for="who">Who:</label>
<select id="who">
</select>
</form>
Please Don't make it duplicate i have a code please refer that and let me where i'm doing wrong Hello guys i have program which deals with the multi select list where I have implemented such functionality where user can Add or Remove item from left side list to right side list ("<" and ">").This Totally works fine Again i have added a Table which contains the right side (selected list values) for this code is :
HTML: In this "sourceHeaderFields" contains the list where we are selecting list adding to the "sourceHeaderFields"
<h2><strong>Select features from Seed data:</strong> </h2>
<select id="sourceHeaderFields" name="sourceHeaderFields" multiple="multiple"
style="width:210Px;height:150px;margin-left: 100px;">
</select>
<select id="sourceHeaderFields" name="targetHeaderFields" multiple="multiple"
style="width:210Px; height:150px">
</select>
<br>
<input type="button" id="leftall" value="<<" style="margin-left: 250px;"/>
<input type="button" id="left" value="<" />
<input type="button" id="right" value=">" />
<input type="button" id="rightall" value=">>" />
<br />
<br></br>
<h2> <strong> Default Values for the Selected Headers: </strong> </h2>
<table id="defaultValuesTable">
</table>
JS
$(function () {
function moveItems(origin, dest) {
$(origin).find(':selected').appendTo(dest);
}
$('#left').click(function () {
selectedValue1 = $('#targetHeaderFields').remove(':selected').val()
//console.log(selectedValue1);
moveItems('#targetHeaderFields', '#sourceHeaderFields');
$("#defaultValuesTable").remove().append("<tr id='"+selectedValue+"'><td>"
+selectedValue+"</td><td><input type='text'></tr>");
});
$('#right').on('click', function () {
selectedValue = $('#sourceHeaderFields').find(':selected').val()
console.log(selectedValue);
moveItems('#sourceHeaderFields', '#targetHeaderFields');
debugger;
//Populate the table with the field
$("#defaultValuesTable").append("<tr id='"+selectedValue+"'><td>"
+selectedValue+"</td><td><input type='text'></tr>");
});
Multilist works fine but problem is this line:for table list****Please go this for live code working: https://jsfiddle.net/8jbp47zq/ not sure how to paste a csv file to get the list
$("#defaultValuesTable").remove().append("<tr id='"+selectedValue+"'><td>"
+selectedValue+"</td><td><input type='text'></tr>");
Here when i'm adding anything its adding a text bar for the table with accoresponding list name but when i'm removing its not removing one by one at once its remove all...i want to remove the table list one by one not at once for that i have tried many way:
//$("#defaultValuesTable").remove(id="+selectedValue1+");
and
//$("#defaultValuesTable").children("tr").remove();
and
//$("#defaultValuesTable").remove().append(id="+selectedValue1+");
none of these worked please help..If you guys need more info please tell me ill give...I have added a pic of web UI please refer that...thnx
There was an issue with the remove process. I've updated the code.
//A drop-down list
$(document).ready(function() {
for (var i = 1970; i <= 2018; i++) {
var fromYearSelect = document.getElementById("fromYear");
var toYearSelect = document.getElementById("toYear");
var option = document.createElement("OPTION");
fromYearSelect.options.add(option);
option.text = i;
option.value = i;
var option2 = document.createElement("OPTION");
toYearSelect.options.add(option2);
option2.text = i;
option2.value = i;
}
});
$(function() {
function moveItems(origin, dest) {
$(origin).find(':selected').appendTo(dest);
}
function moveAllItems(origin, dest) {
$(origin).children().appendTo(dest);
}
$('#left').click(function() {
debugger;
selectedValue1 = $('#targetHeaderFields').remove(':selected').val()
//console.log(selectedValue1);
moveItems('#targetHeaderFields', '#sourceHeaderFields');
debugger; // fixed below line.
$('#'+selectedValue1, "#defaultValuesTable").remove();
//$("#defaultValuesTable").children("tr").remove();
//$("#defaultValuesTable").remove().append(id="+selectedValue1+");
// $("#defaultValuesTable").remove().append("<tr id='" + selectedValue + "'><td>" +
// selectedValue + "</td><td><input type='text'></tr>");
});
$('#right').on('click', function() {
selectedValue = $('#sourceHeaderFields').find(':selected').val()
console.log(selectedValue);
moveItems('#sourceHeaderFields', '#targetHeaderFields');
debugger;
//Populate the table with the field
$("#defaultValuesTable").append("<tr id='" + selectedValue + "'><td>" +
selectedValue + "</td><td><input type='text'></tr>");
});
$('#leftall').on('click', function() {
moveAllItems('#targetHeaderFields', '#sourceHeaderFields');
});
$('#rightall').on('click', function() {
moveAllItems('#sourceHeaderFields', '#targetHeaderFields');
});
$('#populateHeaderFields').on('click', function() {
alert("Inside populate list");
var files = ('#source_fileName').files;
alert("Files Count - " + files);
});
$('#upload-form').on('change', function(evt) {
//alert('File content changed');
debugger;
var filesCount = evt.target.files.length;
for (i = 0; i < filesCount; i++) {
var file = evt.target.files[i];
if (file) {
var reader = new FileReader();
/*
reader.onload = function(e) {
var contents = e.target.result;
var ct = reader.result;
var words = ct.split(' ');
}
reader.readAsText(file);
*/
// Read our file to an ArrayBuffer
reader.readAsArrayBuffer(file);
// Handler for onloadend event. Triggered each time the reading operation is completed (success or failure)
reader.onloadend = function(evt) {
// Get the Array Buffer
var data = evt.target.result;
// Grab our byte length
var byteLength = data.byteLength;
// Convert to conventional array, so we can iterate though it
var ui8a = new Uint8Array(data, 0);
// Used to store each character that makes up CSV header
var headerString = '';
// Iterate through each character in our Array
for (var i = 0; i < byteLength; i++) {
// Get the character for the current iteration
var char = String.fromCharCode(ui8a[i]);
// Check if the char is a new line
if (char.match(/[^\r\n]+/g) !== null) {
// Not a new line so lets append it to our header string and keep processing
headerString += char;
} else {
// We found a new line character, stop processing
break;
}
}
//Iterate through the list and populate the select element..
$.each(headerString.split(","), function(i, e) {
$("#sourceHeaderFields").append($("<option>", {
text: e,
value: e
}));
});
// if len(headerString)!= 1{
// alert("headerString Donot match");
// }else{
console.log(headerString);
console.log("Next Read");
};
} else {
alert("Failed to load file");
}
}
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> upload </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<link href="https://bootswatch.com/4/solar/bootstrap.min.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">
<div class="jumbotron">
<div class="mx-auto" style="width:500px;">
<h1>Large Data Generation</h1>
</div>
</div>
<form id="upload-form" action="{{ url_for('upload') }}" method="POST" enctype="multipart/form-data">
<div id="file-selector">
<p>
<strong>Source File: </strong>
<input id="source_fileName" type="file" name="source_fileName" accept="csv/*" multiple style="
margin-left: 10px;" />
</p>
</div>
<br>
<strong>Location Type:</strong>
<input type="radio" name="target" value="BrowserDownload" checked>Browse Local
<input type="radio" name="target" value="dumpToS3"> S3 Remote
<br> </br>
<h2><strong>Select features from Seed data:</strong> </h2>
<select id="sourceHeaderFields" name="sourceHeaderFields" multiple="multiple" style="width:210Px;height:150px;margin-left: 100px;">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<select id="targetHeaderFields" name="targetHeaderFields" multiple="multiple" style="width:210Px; height:150px">
</select>
<br>
<input type="button" id="leftall" value="<<" style="margin-left: 250px;" />
<input type="button" id="left" value="<" />
<input type="button" id="right" value=">" />
<input type="button" id="rightall" value=">>" />
<br />
<br></br>
<h2><strong>Default Values for the Selected Headers:</strong></h2>
<table id="defaultValuesTable">
</table>
<br>
<div>
<br>
</div>
<div id="div_records">
<strong>Record Count: </strong>
<input id="records" type="text" name="records" value="1000" style="margin-left: 5px;">
<br> <br> <br>
<strong>From Year: </strong>
<select id="fromYear" name="fromYear" style="margin-left: 30px;"></select>
<strong style="margin-left:20px">To Year: </strong>
<select id="toYear" name="toYear" style="margin-left: 5px;"></select>
<br></br>
</div>
<br></br>
<input type="submit" value="Generate Data" id="upload-button">
</form>
</div>
</body>
Remove multiple/all rows one by one from a table with delay use below code.
var i=0;
$('#defaultValuesTable tr').each(function() {
var dly=200;
$(this).delay(i*dly).queue(function(){
$(this).remove();
});
i++;
});
Change value of dly to increase/decrease delay
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(); }
});
I posted this earlier, but deleted the post due to formatting errors. I have a seen a few similar responses but they have been given negative scores so I thought I would post one up.
I have checkboxes that pull names from an SQL list using Ajax (which are echoed as checkboxes) and I want to when they are checked be posted in the textarea below when 'Add Selected Names' is clicked on
Here is my code, it functions for all and selects the figures ok (as the alerts test them). But doesn't pass the values to the textarea.
Jsfiddle:
http://jsfiddle.net/B4PvJ/1/
HTML:
<form name="promoForm4" method=post enctype=multipart/form-data action=cp007.php onSubmit="return validateForm();">
<ul class=mainForm id="mainForm_1">
<select name="nameoflist" onchange="changeFunc(this);">
<option value="" disabled="disabled" selected="selected">Select Recipients</option>
<option value="All Recipients">All Recipients</option>
<option value="Tech_List">Tech List</option>
</select>
<p>
<input type="checkbox" class="checkall">Check All
<br>
<br>
<div id="list_output" style="width:500px;height:500px;overflow:auto;"></div>
<p>Add Selected Names
<p>
<textarea readonly rows="10" cols="100" name="name_list_box"></textarea>
<p class="mainForm">
<input id="saveForm" class="mainForm" type="submit" value="Enter Track Details" />
</li>
</form>
JavaScript:
$(function () {
$(".add_names").click(function () {
alert("clicked");
var allVals = [];
$(".cb:checked").each(function () {
allVals.push($(this).val());
});
alert(allVals);
});
});
function changeFunc(obj) {
$('.checkall').prop('checked', false);
$("#list_output").empty();
var selectedValue = obj.options[obj.selectedIndex].value;
var url = "getnames.php?list_name=" + selectedValue;
$.get(url, function (data, status) {
var recep_list = data.split("^");
var r_len = recep_list.length;
for (var i = 0; i < r_len; i++) {
recep = recep_list[i].split("~");
$('#list_output').append('<input type="checkbox" class="cb" value="' + recep[1] + '" /> ' + recep[0] + '<br>');
}
});
}
$(".add_names").click(function () {
alert("clicked");
var allVals = [];
$(".cb").each(function () {
allVals.push($(this).val());
alert("somethingchecked");
});
var stringvals = allVals.join(" ");
$("#name_list_box").val($("#name_list_box").val() + stringvals);
alert(allVals);
});
$(".checkall").click(function () {
$('#list_output .cb').prop('checked', this.checked);
});
Many thanks
CP
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