I have a text box. When I click on the listed data (Data is getting from table). I need to set response table row ID in text box.
I need data to set like this "|13456|1400|14567|" in the text box.
Please help me to set id in text box. Currently I can set only one ID.
Please find the attached image
JS
$.post("getDetailsAjax.php", {keywords: keywords}, function(data){
$.each(data, function() {
var leftboxid = this.id;
var producer = this.producer;
var model = this.model;
var typ = this.typ;
var body = this.body;
var date_from = this.date_from;
var date_to = this.date_to;
var power = this.power;
var engine_code = this.engine_code;
var fuel = this.fuel;
var ccm = this.ccm;
var cylinders = this.cylinders;
$('#search-result').append('<div class="leftboxid_'+leftboxid+'" data-leftbox="' +leftboxid+ '"><a href="#" class="list-group-item"><p class="list-group-item-text">' +producer+ ' '+model+' '+typ+' ('+body+')</p><p class="list-group-item-text">' +date_from+ ' to ' +date_to+ '</p> <p class="list-group-item-text">' +power+' ps .' +engine_code+' . ' +fuel+ ' . '+ccm+' ccm . ' +cylinders+ ' cyl</p></div>');
/* right box */
$(".leftboxid_"+leftboxid).on("click", function(){
var setID = $(this).attr("data-leftbox");
$(".append-left-id").attr("value", setID);
});
});
}, "json");
Textbox
<div class="col-xs-4">
<input type="text" class="form-control append-left-id" placeholder="Result Field">
</div>
I think you want this
instead of this code:
$(".leftboxid_"+leftboxid).on("click", function(){
var setID = $(this).attr("data-leftbox");
$(".append-left-id").attr("value", setID);
});
use this :
$(".leftboxid_"+leftboxid).on("click", function(){
var setID = $(this).attr("data-leftbox");
$(".append-left-id").val($(".append-left-id").val()+"|"+setID);
});
You can append like so:
.....
var setID = $(this).attr("data-leftbox");
var val = $(".append-left-id").val();
$(".append-left-id").val(val+"|"+setID );
....
Related
I am trying to create a dynamic form with Javascript, where it is possible to add more fields. And when the user starts typing in the added fields then suggestions should show based on a list. Suggested inputs based on written input
The added fields should look just like the one shown in 1. The Search function works by using querySelector to take the new field created. However, i receive a type error saying: TypeError: Cannot read properties of null.
The function works without newSearch(i), but i want to have this suggestion box appearing when adding more fields.
Source Code:
sites.html
<div class="sites-container">
<form class="sites-form" method = "POST" id="myForm" name="myForm">
<div class="wrapper">
<div id="Site-options">
<h1 class="sites-add-header"> Create a String </h1>
<p class="sites-add-text"> Choose Modules at String </p>
<div class="wrapper2">
<div class="search-input2">
<a href="" target="_blank" hidden></a>
<input type="text" placeholder="Type to search.." name="PV-modules">
<div class="autocom-box2">
</div>
<div class="icon2"><i class="fas fa-search"></i></div>
</div>
</div>
</div>
<div class="controls">
<i class="fa fa-plus"></i>Add Another String
<i class="fa fa-plus"></i>Remove Site
</div>
</div>
<button type="submit" class="sites-add-site button">Add Site</button>
</form>
</div>
<script>
let suggestions2 = {{ modules | safe}} ;
</script>
<script src="{{ url_for('static', filename='add-site.js') }}"></script>>
add-site.js
var site_options = document.getElementById('Site-options');
var add_more_fields = document.getElementById('add_more_fields');
var remove_fields = document.getElementById('remove_fields');
var count = 1;
add_more_fields.onclick = function(){
var i = count++;
var _div = document.createElement('div');
_div.setAttribute('id','new-div'+i);
_div.innerHTML = '<p class="sites-add-text"> Choose Modules at Site </p>' +
'<div class="wrapper2">' +
'<div class="search-input2" id="new-search-input' + i + ' ">' +
'<a href="" target="_blank" hidden></a>' +
'<input type="text" placeholder="Type to search.." name="PV-modules">' +
'<div class="autocom-box2 id="new-autocom-box' + i + '">' +
'</div>'+
'<div class="icon2" id="new-icon' + i + '><i class="fas fa-search"></i></div>'+
'</div>'+
'</div>';
newSearch(i);
site_options.appendChild(_div);
};
remove_fields.onclick = function(){
var elem = document.getElementById("new-div");
elem.parentNode.removeChild(elem);
}
function newSearch(i) {
// getting all required elements
var searchWrapper2 = document.querySelector("#new-search-input" + i);
var inputBox2 = searchWrapper2.querySelector("input"); // <- Here i get TypeError
var suggBox2 = searchWrapper2.querySelector(".autocom-box2");
var icon2 = searchWrapper2.querySelector(".icon2");
let linkTag2 = searchWrapper2.querySelector("a");
let webLink2;
// if user press any key and release
inputBox2.onkeyup = (e2)=>{
let userData2 = e2.target.value; //user enetered data
let emptyArray2 = [];
if(userData2){
icon2.onclick = ()=>{
webLink2 = `https://www.google.com/search?q=${userData2}`;
linkTag2.setAttribute("href", webLink2);
linkTag2.click();
}
emptyArray2 = suggestions2.filter((data2)=>{
//filtering array value and user characters to lowercase and return only those words which are start with user enetered chars
return data2.toLocaleLowerCase().startsWith(userData2.toLocaleLowerCase());
});
emptyArray2 = emptyArray2.map((data2)=>{
// passing return data inside li tag
return data2 = `<li>${data2}</li>`;
});
searchWrapper2.classList.add("active"); //show autocomplete box
showSuggestions2(emptyArray2);
let allList2 = suggBox2.querySelectorAll("li");
for (let i = 0; i < allList2.length; i++) {
//adding onclick attribute in all li tag
allList2[i].setAttribute("onclick", "select2(this)");
}
}else{
searchWrapper2.classList.remove("active"); //hide autocomplete box
}
}
function select2(element){
let selectData2 = element.textContent;
inputBox2.value = selectData2;
icon2.onclick = ()=>{
webLink2 = `https://www.google.com/search?q=${selectData2}`;
linkTag2.setAttribute("href", webLink2);
linkTag2.click();
}
searchWrapper2.classList.remove("active");
}
function showSuggestions2(list){
let listData2;
if(!list.length){
userValue2 = inputBox2.value;
listData2 = `<li>${userValue2}</li>`;
}else{
listData2 = list.join('');
}
suggBox2.innerHTML = listData2;
}
}
you need to call newSearch after adding the element
site_options.appendChild(_div);
newSearch(i);
and you need to remove extra space in the innerHTML, which is why id attribute doesn't get found, breaking all the code:
'<div class="search-input2" id="new-search-input' + i + '">' +
swap these two lines it should work fine . searchWrapper2 is null in your case.
newSearch(i); site_options.appendChild(_div);
site_options.appendChild(_div); newSearch(i);
I have asked something similar in the past but was able to resolve it by separating the functions by events. I need to be able to pass 2 href events in one Onchange Event because it is a dropdown, OR I need to be able to tie the second function into another Event.
This works only when an alert() is inserted. Once I take the alert() out it does not work. I've tried to supress the alert while still keeping it in the code and it works fine. I do not want the alert but I want the results.
HTML Here:
<select id="PartList" class="form-control form-control-lg ml-0" onChange="SelectMain();">
JavaScript Here
function sList() {
var pl = document.getElementById("PartList");
var value = pl.options[pl.selectedIndex].value;
var text = pl.options[pl.selectedIndex].text;
str = 'URL1 HERE='+ "'" + text + "'" ;
//alert(value);
//alert(text);
window.location.href = str;
}
function SelectValue() {
var pv = document.getElementById("PartList");
var value = pv.options[pv.selectedIndex].value;
str = 'URL2 HERE' + value ;
alert(value);
window.location.href = str;
}
function SelectMain() {
sList();
SelectValue();
}
function alert(message) {
console.info(message);
}
This is resolved, for those that come to this question. The problem wasn't with the JavaScript it was because the device I was sending the commands to couldn't handle the commands that fast. I have incorporated the resolved code with troubleshooting techniques.
function sList() {
var pl = document.getElementById("PartList");
var value = pl.options[pl.selectedIndex].value;
var text = pl.options[pl.selectedIndex].text;
str = 'URL1='+ "'" + text + "'" ;
//str1 = 'http://google.com';
//alert(value);
//alert(text);
window.location.href = str;
//window.open(str1);
}
function SelectValue() {
setTimeout(function(){
var pv = document.getElementById("PartList");
var value = pv.options[pv.selectedIndex].value;
str = 'URL2=' + value ;
//str1 = 'http://aol.com';
//alert(value);
window.location.href = str;
//window.open(str1);
},1000);
}
I'm struggling to understand how I change which variable is being added to in a function.
Essentially, when a user chooses a hotel, it needs to be added to hotelSelection. When they click next, it updates a map with restaurants, and when they choose restaurants, it needs to go into restaurantSelection. That's the bit I'm stuck on, changing it from hotel selection to restaurant selection.
Here's a snippet:
var hotelSelection = "";
var restaurantSelections = "";
var sightSelections = "";
function chooseSelection(resultIndex) {
var locationName = document.getElementById('locationName-' + resultIndex);
hotelSelection = `<div class="input-group" id="Hotel-chosen">
<li class="list-group-item">
<strong>${locationName.innerHTML}</strong><br>`;
var locationRating = document.getElementById('locationRating-' +
resultIndex);
hotelSelection += `rating: ${locationRating.innerHTML}</li>`
console.log("Hotel Selection: " + hotelSelection);
}
Any help would be really appreciated!
This gets to the heart of how a function can communicate. What you are doing is accessing a variable in a higher "closure." This has its good and bad points, and one of the bad points which you're finding now is that it isn't very flexible.
If instead of doing it this way you were able to use the return value of the function, you would have the flexibility to do what you're saying. For example:
var hotelSelection = "";
var restaurantSelections = "";
var sightSelections = "";
function chooseSelection(resultIndex) {
var locationName = document.getElementById('locationName-' + resultIndex);
var selection = `<div class="input-group" id="Hotel-chosen">
<li class="list-group-item">
<strong>${locationName.innerHTML}</strong><br>`;
var locationRating = document.getElementById('locationRating-' +
resultIndex);
selection += `rating: ${locationRating.innerHTML}</li>`
console.log("Hotel Selection: " + hotelSelection);
return selection;
}
If you do this, then when you call the function you just assign the return value to a variable, like this:
hotelSelection = chooseSelection(someIndex);
sightSelections = chooseSelection(someIndex);
Hi all i have code for multiple upload image, but i want only one image per upload. so I create the input file every time I clicked the upload button with the dynamic id. however I have problems checking whether the user chooses the file to upload or press the cancel button. because if the user pressed the cancel button I want to delete the input file I have created. for full sourcenya as below:
$(document).ready(function () {
$("#btnimg").click(function () {
//check input file id number
var counter = $("input[id^='upload']").length;
//add input file every btnimg clicked
var html = "<input type='file' id='upload_" + counter + "' style='display:none;'/>";
$("#result").append(html);
//trigger to dialog open file
var upload = $('#upload_' + counter);
upload.trigger('click');
upload.on('change', function () {
console.log('change fire...');
var inputFiles = this.files;
var inputFile = inputFiles[0];
var reader = new FileReader();
reader.onload = function (evt) {
var imghtml = "<img id='img_upload_" + counter + "' src='" + evt.target.result + "' width='50px;' height='50px;'/>";
$('#previewimage').append(imghtml);
};
reader.onerror = function (event) {
alert("something: " + event.target.error.code);
};
reader.readAsDataURL(inputFile);
});
//if file not selected or user press button cancel on open dialog
//upload.remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="result"></div>
<button id="btnimg">upload image</button>
<div id="previewimage">
</div>
</body>
thank you in advance,
You can check the .length of <input type="file"> element .files property to determine if a file is selected by user
That all sounds like an xy-problem to me.
I have not (yet) got a response from you about the why you want to do it, so I will base my answer on two probable situations:
If you want to keep track of the selected Files, in order to be able to do anything with them later (e.g send them through AJAX), then use a single <input>.
At every change event, you will store the new File in an Array, from where you will also be able to do something with later on:
(function() {
// this Array will hold our files, should be accessible to the final function 'doSomething'
var savedFiles = [];
var counter = 0;
var upload = $('#upload');
upload.on('change', onuploadchange);
$("#btnimg").click(function routeClick() {
upload.trigger('click');
});
$('#endbtn').click(function doSomething() {
console.log(savedFiles);
});
function onuploadchange() {
var inputFiles = this.files;
var inputFile = inputFiles[0];
if (!inputFile) { return; } // no File ? return
savedFiles.push(inputFile); // save this File
// don't use a FileReader here, useless and counter-productive
var url = URL.createObjectURL(inputFile);
var imghtml = "<img id='img_upload_" + counter + "' src='" + url + "' width='50px;' height='50px;'/>";
$('#previewimage').append(imghtml);
$('#endbtn').removeAttr('disabled');
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result">
<!-- A single input to save them all-->
<input type='file' id='upload' style='display:none;' />
</div>
<button id="btnimg">upload image</button>
<div id="previewimage">
</div>
<button id="endbtn" disabled>do something with saved files</button>
If, for an obscure reason, you absolutely need to keep all the filled <input> elements in your document, then create a new one only if the last one is itself filled.
$(document).ready(function() {
$("#btnimg").click(function() {
// grab previous ones
var inputs = $("input[id^='upload']");
// get the last one we created
var last = inputs.last();
var counter = inputs.length;
console.log(counter);
var upload;
// if there is no input at all, or if the last one is already filled with a File
if (!last.length || last[0].files.length) {
console.log('create new input');
upload = makeNewInput();
} else {
// use the last one
upload = last;
}
//trigger to dialog open file
upload.trigger('click');
function makeNewInput(counter) {
var html = "<input type='file' id='upload_" + counter + "' style='display:none;'/>";
var el = $(html);
el.on('change', onuploadchange);
$('#result').append(el);
return el;
}
function onuploadchange() {
var inputFiles = this.files;
var inputFile = inputFiles[0];
var url = URL.createObjectURL(inputFile);
var imghtml = "<img id='img_upload_" + counter + "' src='" + url + "' width='50px;' height='50px;'/>";
$('#previewimage').append(imghtml);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
<button id="btnimg">upload image</button>
<div id="previewimage">
</div>
I have a custom jQuery script that works fine in all bowsers but one (Explorer 6, 7, 8?).
The purpose of the code is to allow a user to add multiple form fields to their form (if the user want more than one phone number or more than one web address).
It is written so that any "A" tag with a class containing "add" is bound to the jQuery function.
The error I am getting is as follows:
///////////////////////////////
Line: 240
Char: 5
Error: 'this.id.3' is null or not an object
Code: 0
///////////////////////////////
HTML of form:
(please note that I am aware that the form tags are not here, this is a small portion of a larger form.
<ul>
<li>
<ul>
<li class="website">
<input id="website1_input" name="website[1][input]" type="text" value="www.test.org"/>
<input type="checkbox" id="website1_delete" name="website[1][delete]" class="element radio" value="1" />
<label for="website1_delete">Delete</label>
</li>
</ul>
add another website
</li>
</ul>
And now the jQuery:
There should be on a page a ul containing at least one li.
All the lis should have a certain class like "phone" or "address"
After the /ul There should be a link with a matching id, like
"addPhone" or "addAddress". The href attribute should be "#".
function makeAddable(theClass) {
$('#add' + theClass[0].toUpperCase() + theClass.substr(1)).click(function() {
var numItems = $('.' + theClass).length;
var newItem = $('.' + theClass).eq(numItems - 1).clone();
newItem.find('input[type=text]').val('');
numItems++; // number in the new IDs
// keep ids unique, linked to label[for], and update names
// id & for look like: phone1_type, phone1_ext, phone13_p1, etc.
// names look like: phone[1][type], phone[1][ext], phone[13][p1], etc.
newItem.find('[id^=' + theClass + ']').each(function(i) {
var underscoreIndex = this.id.indexOf('_');
var idNum = this.id.substring(theClass.length, underscoreIndex);
this.id = this.id.replace(idNum, numItems);
});
newItem.find('[for^=' + theClass + ']').each(function(i) {
var jqthis = $(this);
var forAttr = jqthis.attr('for');
var underscoreIndex = forAttr.indexOf('_');
var idNum = forAttr.substring(theClass.length, underscoreIndex);
forAttr = forAttr.replace(idNum, numItems);
jqthis.attr('for', forAttr);
});
newItem.find('[name^=' + theClass + ']').each(function(i) {
var jqthis = $(this);
var nameAttr = jqthis.attr('name');
var bracketIndex = nameAttr.indexOf(']');
var idNum = nameAttr.substring(theClass.length + 1, bracketIndex);
nameAttr = nameAttr.replace(idNum, numItems);
jqthis.attr('name', nameAttr);
});
$(this).prev('ul').append(newItem);
return false;
});
}
// Automatically enable all <a href="#" id="addSomething"> links
$(function() {
$('a[href=#][id^=add]').each(function(i) {
makeAddable( this.id[3].toLowerCase() + this.id.substr(4) );
});
});
this.id.charAt(3).toLowerCase()
Change this...
this.id[3]
To this...
this.id.substr(3, 1);
Something like this will achieve the same affect but makes greater use of jquery, thereby avoiding the crossbrowser compatibility problems so common with javascript:
function addInput(inputType) {
var items, itemNumber, lastItem, newListItem, parentList, inputName, inputId, deleteId, thisId;
items = $('li.' + inputType);
itemNumber = items.length + 1;
lastItem = $(items[itemNumber-2]);
newListItem = lastItem.clone();
parentList = lastItem.parents('ul:first');
inputId = inputType + itemNumber + '_input';
deleteId = inputType + itemNumber + '_delete';
$(':input', newListItem).each(function() {
inputName = $(this).attr('name').replace(/\[\d*\]/, '['+itemNumber+']');
thisId = $(this).attr('id').match(/_delete/) ? deleteId : inputId
$(this)
.val('')
.removeAttr('checked')
.attr('id', thisId)
.attr('name', inputName)
}).end()
.find('label').attr('for', deleteId).end()
.appendTo(parentList)
;
}
$(function() {
$('a[href=#][id^=add]').live('click', function() {
addInput(this.id.substr(3).toLowerCase());
});
});