Adding checkboxes to textarea in JavaScript - javascript

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

Related

Issue in Executing the jquery program for multi select list with (table)

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

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

Find all inputs within a jquery object

I have a little problem with my template.
I would like to read in a template with jquery and then find all inputs within this object to manipulate them.
Unfortunately, the inputs are not returned.
I already use the function "checkInputs" in another place.
The target is not a template and it works without problems.
Here's my test code:
listOfTemplateInputs = checkInputs("#IncomingInformationsTemplate");
alert("Hidden: " + listOfTemplateInputs.Hidden.length + ", Fields: " + listOfTemplateInputs.Fields.length);
function checkInputs(target) {
var ListOfFields = [];
var ListOfCheckBoxes = [];
var ListOfHidden = [];
$(target + " input[type='text'], textarea, input[type='password']").each(function() {
var input = $(this);
ListOfFields.push(input);
});
$(target + " input[type='checkbox']").each(function() {
var input = $(this);
ListOfCheckBoxes.push(input);
});
$(target + " input[type='hidden']").each(function() {
var input = $(this);
ListOfHidden.push(input);
});
var inputList = {
Fields: ListOfFields,
CheckBoxes: ListOfCheckBoxes,
Hidden: ListOfHidden
};
return inputList;
}
And here is my template:
<script id="IncomingInformationsTemplate" type="text/html">
<tr class="">
<input autocomplete="off" name="IncomingInformations.Index" type="hidden" value="5eda7c21-9b4e-4eb5-b992-6a3ea16a46cd" />
<td>
<div>
<input type="hidden" name="country" value="Norway">
<input type="hidden" name="country2" value="Germany">
<input type="text" name="Name" value="Tom">
<input type="text" name="Name2" value="Lisa">
</div>
</td>
</tr>
</script>
The thing is that script tag does not parse the HTML and create a DOM out of it.
Its contents are just a string.
To be able to select from it, you should parse it (you can do it with jQuery) and select from the created (parsed) object.
Notice in the code below I first create a "mini (virtual) DOM" out of your template's text contents:
var miniDOM = $($(target).text());
And now use all selectors having it as context/root. E.g.
miniDOM.find("input[type='text'], textarea, input[type='password']").each(function() {
This finds the elements as you wanted.
listOfTemplateInputs = checkInputs("#IncomingInformationsTemplate");
alert("Hidden: " + listOfTemplateInputs.Hidden.length + ", Fields: " + listOfTemplateInputs.Fields.length);
function checkInputs(target) {
var miniDOM = $($(target).text());
var ListOfFields = [];
var ListOfCheckBoxes = [];
var ListOfHidden = [];
miniDOM.find("input[type='text'], textarea, input[type='password']").each(function() {
var input = $(this);
ListOfFields.push(input);
});
miniDOM.find("input[type='checkbox']").each(function() {
var input = $(this);
ListOfCheckBoxes.push(input);
});
miniDOM.find("input[type='hidden']").each(function() {
var input = $(this);
ListOfHidden.push(input);
});
var inputList = {
Fields: ListOfFields,
CheckBoxes: ListOfCheckBoxes,
Hidden: ListOfHidden
};
return inputList;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script id="IncomingInformationsTemplate" type="text/html">
<tr class="">
<input autocomplete="off" name="IncomingInformations.Index" type="hidden" value="5eda7c21-9b4e-4eb5-b992-6a3ea16a46cd" />
<td>
<div>
<input type="hidden" name="country" value="Norway">
<input type="hidden" name="country2" value="Germany">
<input type="text" name="Name" value="Tom">
<input type="text" name="Name2" value="Lisa">
</div>
</td>
</tr>
</script>
Of course, you could, alternatively, turn that script into any renderable element, like div or span, even if hidden, and you could query it with your original code:
listOfTemplateInputs = checkInputs("#IncomingInformationsTemplate");
alert("Hidden: " + listOfTemplateInputs.Hidden.length + ", Fields: " + listOfTemplateInputs.Fields.length);
function checkInputs(target) {
var ListOfFields = [];
var ListOfCheckBoxes = [];
var ListOfHidden = [];
$(target + " input[type='text'], textarea, input[type='password']").each(function() {
var input = $(this);
ListOfFields.push(input);
});
$(target + " input[type='checkbox']").each(function() {
var input = $(this);
ListOfCheckBoxes.push(input);
});
$(target + " input[type='hidden']").each(function() {
var input = $(this);
ListOfHidden.push(input);
});
var inputList = {
Fields: ListOfFields,
CheckBoxes: ListOfCheckBoxes,
Hidden: ListOfHidden
};
return inputList;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="IncomingInformationsTemplate" style="display: none">
<tr class="">
<input autocomplete="off" name="IncomingInformations.Index" type="hidden" value="5eda7c21-9b4e-4eb5-b992-6a3ea16a46cd" />
<td>
<div>
<input type="hidden" name="country" value="Norway">
<input type="hidden" name="country2" value="Germany">
<input type="text" name="Name" value="Tom">
<input type="text" name="Name2" value="Lisa">
</div>
</td>
</tr>
</div>
you should find inputs with this method
$('#IncomingInformationsTemplate').find(':input').each(function(i,e) {
console.log((i+1)+'. '+$(e)[0].outerHTML);
$(e).addClass('manipulate-it'); //manipulate it
});

Checkbox select deselect all and perform function

I have a bunch of checkboxes that when clicked pass their value to a text area. I then have a checkbox that when clicked selects all the other checkboxes. This is all working fine. What I would like to do is have the checkboxes perform their functions when select all is clicked. It works at the moment, but only when I refresh the page. I would like it to happen when select all is clicked.
Here's what I've been playing with so far:
function setAllCheckboxes(divId, sourceCheckbox) {
divElement = document.getElementById(divId);
inputElements = divElement.getElementsByTagName('input');
for (i = 0; i < inputElements.length; i++)
$('.checkbox').each(function() {
this.checked = true;
this.click();
});
{
if (inputElements[i].type != 'checkbox')
continue;
inputElements[i].checked = sourceCheckbox.checked;
}
}
If you're already using jQuery, you could do it without loops, with jQuery's .on()/.trigger()/.change():
var $result = $('.js-result');
var $checkboxes = $('.js-checkbox');
$checkboxes.on('change', function(e) {
var $checkbox = $(e.target);
$result.append(
'<div>' +
$checkbox.closest('.js-label').text() + ' is ' +
($checkbox.prop('checked') ? 'checked' : 'unchecked') +
'</div>'
);
});
$('.js-button').on('click', function() {
var $this = $(this);
$checkboxes.prop('checked', !$this.data('checked'));
$checkboxes.trigger('change');
$this.data('checked', !$this.data('checked'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="js-label">
<input type="checkbox" class="js-checkbox"/>
Checkbox 1
</label>
<label class="js-label">
<input type="checkbox" class="js-checkbox"/>
Checkbox 2
</label>
<label class="js-label">
<input type="checkbox" class="js-checkbox"/>
Checkbox 3
</label>
<button type="button" class="js-button">Check/uncheck all</button>
<div class="js-result"></div>
JSFiddle
CheckBox should be handled with onchange event.
Below code I am firing an event whenever the checkbox checked programmatically.
Below code may help you
function setAllCheckboxes(divId, sourceCheckbox) {
divElement = document.getElementById(divId);
inputElements = divElement.getElementsByTagName('input');
for (i = 0; i < inputElements.length; i++)
$('.checkbox').each(function() {
this.checked = true;
/* this.click(); */
this.fireevent('onChange');
/* or you can call this.onChange(); */
});
{
if (inputElements[i].type != 'checkbox')
continue;
inputElements[i].checked = sourceCheckbox.checked;
}
}
In case you are using only java script.
Below is the very simple running example. which consumes short time without any use of external library as JQuery
HTML code
<html>
<head>
<title>test</title>
<script>
function amend(a)
{
document.getElementById("ta").value += a;
}
function checkAll()
{
var textboxes = document.getElementsByClassName("cb");
for(i=0;i<textboxes.length;i++)
{
textboxes[i].checked=true;
textboxes[i].onchange();
}
}
</script>
</head>
<body>
<textarea rows="4" cols="50" id="ta">
Below the outputs
</textarea>
<div id="checkdiv">
<input type="checkbox" onChange="amend(this.value)" value="data to add 1" class="cb">First</input>
<br>
<input type="checkbox" onChange="amend(this.value)" value="data to add 2" class="cb">Second</input>
<br>
<input type="checkbox" onChange="amend(this.value)" value="data to add 3" class="cb">Third</input>
<br>
<input type="checkbox" onChange="checkAll()">Check all</input>
</div>
</body>
</html>

change the Input Name based on the multiple dropdown selection in html form?

I am trying to create add/remove form fields dynamically with jQuery where the user can submit multiple queries based on the dropdown selections. At the end, it should generate URL with a combination of selection.So far I have managed to create add/remove form fields with the option of multiple queries.
For example, if the user submits input for a car then it will generate URL like:
exmaple.com/?car=xxx
and which is working.
If a user submits input for car and bike then it should generate:
exmaple.com/?car=xxx&bike=yyy
but it is generating like:
exmaple.com/?car=xxx&car=yyy
So how can I solve this issue? Thank you in advance.
$(function() {
$.fn.addmore = function(options) {
var moreElement = this,
singlePreSelectedValue = '',
selectedValue = [],
defaultOption = {
addText: 'add more',
removeText: 'Remote',
selectBoxDuplicate: true,
avoidDuplicationSelection: function(e) {
var o = e;
if ($.inArray($(o).val(), selectedValue) != -1) {
$(o).val(singlePreSelectedValue);
alert('Value already selected.');
} else {
var hasSelectValue = true;
$.each($('.removeDuplication'), function(i, v) {
if ($(this).val() == 'select') {
hasSelectValue = false;
return false;
}
});
}
},
prevSelectedValue: function(e) {
var o = e;
selectedValue = [];
$.each($('.removeDuplication'), function(i, v) {
if ($(this).val() != 'select') {
selectedValue.push($(this).val());
}
});
singlePreSelectedValue = $(o).val();
}
}
defaultOption = $.extend(true, defaultOption, options);
/* $(this).find('select').prepend('<option value="select" selected>Select</option>');*/
$(moreElement).after('' + defaultOption.addText + '');
$('[data-id="more"]').click(function() {
var dataMore = this,
removeDuplication = [];
$(dataMore).before($(moreElement).clone().find('input').not('input[type="submit"]').val('').end().end().find('select.removeDuplication').focus(function() {
if (!defaultOption.selectBoxDuplicate) {
defaultOption.prevSelectedValue(this);
}
}).change(function() {
if (!defaultOption.selectBoxDuplicate) {
defaultOption.avoidDuplicationSelection(this);
}
}).end().append(function() {
return $('<i class="fa fa-trash"></i> ' + +'').click(function() {
$(this).parent().remove();
});
}));
if (!defaultOption.selectBoxDuplicate) {
$.each($('.removeDuplication'), function(i, v) {
if ($(this).val() != 'select') {
removeDuplication.push($(this).val());
}
});
$.each(removeDuplication, function(i, v) {
$('.removeDuplication').last().find('option[value="' + removeDuplication[i] + '"]').remove();
});
}
});
$('.removeDuplication').focus(function(e) {
defaultOption.prevSelectedValue(this);
}).change(function() {
defaultOption.avoidDuplicationSelection(this);
});
return this;
}
$('dl').addmore({
addText: 'Add',
removeText: 'Remove',
selectBoxDuplicate: false
});
});
$(document).ready(function() {
$("select").change(function() {
var str = $(this).val();
$("#searchtermid").attr("name", str);
});
});
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<form class="navbar-form" action="" method="get" action="demo_form.asp">
<dl>
<select class="removeDuplication">
<option value="car">Car</option>
<option value="bike">Bike</option>
<option value="plane">Plane</option>
</select>
<textarea class="form-control custom-control" name="car" id="searchtermid" placeholder="Search term" data-toggle="tooltip" data-placement="bottom" rows="3" style="resize:none" required></textarea>
</dl>
<input class="btn btn-primary" type="submit" value="Submit">
</form>
After getting input from Standard Quality, I have modified my scripts and html.
https://jsfiddle.net/paul85/wjhqszmg/
But still is not letting the user submit input form. Most important, when user will submit from it should redirect to a page for correctly generated URL.
If user submit input for car and bike then redirecting page address or URL will be:
exmaple.com/?car=xxx&bike=yyy
HTML
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<form id="main-form" class="navbar-form" action="/results.html" method="get">
<div class="input_fields_wrap">
<div class="form-field">
<select class="removeDuplication">
<option value="car" >Car</option>
<option value="bike">Bike</option>
<option value="plane">Plane</option>
</select>
<textarea class="form-control custom-control" name="car" id="searchtermid" placeholder="Search term" data-toggle="tooltip" data-placement="bottom" rows="3" style="resize:none"></textarea>
</div>
</div>
<button class="add_field_button">Add More Fields</button>
<input class ="btn btn-primary" type="submit" value="Submit" >
</form>
JAVASCRIPT
$(document).ready(function() {
var max_fields = 3; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var form = $('#main-form');
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div class="form-field">\
<select class="removeDuplication">\
<option value=""></option>\
<option value="car">Car</option>\
<option value="bike">Bike</option>\
<option value="plane">Plane</option>\
</select>\
<textarea class="form-control custom-control" name="car" id="searchtermid" placeholder="Search term" data-toggle="tooltip" data-placement="bottom" rows="3" style="resize:none"></textarea>\
Remove\
</div>'); //add input box
} else {
alert("Sorry, you have reached maximum add options.");
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
});
$(document).on('change','select.removeDuplication',function(e) {
e.preventDefault();
var cI = $(this);
var others=$('select.removeDuplication').not(cI);
$.each(others,function(){
if($(cI).val()==$(this).val() && $(cI).val()!="") {
$(cI).val('');
alert($(this).val()+' already selected.');
}
});
});
/*$(form).submit(function(e){*/
form.on('submit', function(e) {
e.preventDefault()
var queries = [];
var slectedall=true;
var fillupfield=true;
form.find('.form-field').each(function(index, field) {
var query = {};
query.type = $(field).find('select').val();
query.value = $(field).find('textarea').val();
if (query.type !=""){
queries.push(query);
} else{
slectedall=false;
}
});
for (i = 0; i < queries.length; i += 1) {
var query = queries[i];
if (query.value.trim() ===""){
fillupfield=false;
}
};
if (slectedall===false){
alert('Please select option.');
} else {
if (fillupfield===false){
alert('Please insert your searchterm.');
} else {
$("form").submit();
}
}
});
});
It looks like you're extending jQuery, which isn't necessary for this, and is contributing to making the code much less legible. To be honest, I haven't even dug through it to find the problem -- instead, I wrote something from scratch. StackOverflow snippets don't allow forms, so here's a working JSBin: http://jsbin.com/gokodaluna/edit?html,js,output
(Note that I've changed your HTML markup a little bit)
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<form id="main-form" class="navbar-form" action="" method="get" action="demo_form.asp">
<div class="fields">
<div class="form-field">
<select class="removeDuplication">
<option value="car">Car</option>
<option value="bike">Bike</option>
<option value="plane">Plane</option>
</select>
<textarea class="form-control custom-control" name="car" id="searchtermid" placeholder="Search term" data-toggle="tooltip" data-placement="bottom" rows="3" style="resize:none" required></textarea>
</div>
</div>
<input class="btn btn-secondary" type="button" value="Add" id="form-add">
<input class="btn btn-primary" type="submit" value="Submit">
</form>
<h2 id="final-url"></h2>
</body>
</html>
Javascript:
/* Save your initial variables */
var form = $('#main-form');
var formFields = form.find('.fields')
var addButton = $('#form-add');
var emptyInput = $('.form-field').clone(); // clone this at initialization so we always have an empty field
var finalUrl = $("#final-url");
addButton.on('click', function() {
emptyInput.clone().appendTo(formFields);
/* clone this again so our initial field is always empty and available */
})
form.on('submit', function(e) {
e.preventDefault()
var queries = [];
form.find('.form-field').each(function(index, field) {
var query = {};
query.type = $(field).find('select').val();
query.value = $(field).find('textarea').val();
queries.push(query);
});
var url = window.location.href;
for (i = 0; i < queries.length; i += 1) {
var query = queries[i];
var ampOrQ = (i === 0) ? "?" : "&";
url += ampOrQ + query.type + "=" + query.value;
}
/* print the URL into the dom if you want to see it working */
finalUrl.text(url);
/* or forward users to the new URL you've generated */
window.location.href = url;
})
Edit: in the revised code in your question, you're calling $("form").submit() in that if-else statement. When you trigger this, the larger function is still catching the submit event, so it's immediately running e.preventDefault() again. If you need to simply forward the user to the new URL, just set it with window.location.href =. See the last few lines of my (edited) code above.

Categories

Resources