JS Autocomplete - Fire event on document onchange, with value from autocomplete function - javascript

I'm new to JS
I currently have two functions.
The both work as they should.
However, I cannot use the value from the first document function and fire the onchange event in the second and use the selected value.
I would like the selected value from the first script to fire the onchange event in the second script.
Please help!
Html:
<td>
<input type="text" name="product[]" placeholder="Product"
class="product"
onfocus="javascript:$(this).autocomplete('search','');">
</td>
1: Auto complete:
$(function () {
var validOptions = <? echo $get_product_names ?>;
previousValue = "";
$(".product")
.autocomplete({
source: validOptions,
select: function( event, ui ) {alert($(this).val())},
minLength: 0
}).keyup(function () {
var isValid = false;
for (i in validOptions) {
if (validOptions[i].toLowerCase().match(this.value.toLowerCase())) {
isValid = true;
}
}
if (!isValid) {
this.value = previousValue
} else {
previousValue = this.value;
}
}).click(function () {
$(this).autocomplete('search', $(this).val())
});
});
2nd: Generate Pricing:
$(document).on('change', '.product, .width, .drop', function () {
var product = $(".product", $(this).parent().parent()).val();
//alert(product);
var width = $(".width", $(this).parent().parent()).val();
var drop = $(".drop", $(this).parent().parent()).val();
var sub_total = $(".total", $(this).parent().parent());
if (product === "" || width === "" || drop === "") {
var parent = sub_total.val(0);
}
if (product !== "" && width !== "" && drop !== "") {
$.ajax({
url: "#",
method: "POST",
data: {
"product": product,
"width": width,
"drop": drop
},
success: function (data) {
if (data === "") {
var parent = sub_total.val(0);
}
else {
var parent = sub_total.val(data);
}
calculate(parent);
}
});
}
});

For future readers:
I switched over to chosen
My code looks like this now.
<td>
<select data-placeholder="Choose Type" name="product[]"
class="product chosen-select" tabindex="2"
style="width: 150px">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</td>
js:
//trigger product change
$('.product').click(function () {
$('.product').trigger("chosen:updated");
});
$(document).on('change', '.product, .width, .drop', function () {
var product = $(".product", $(this).parent().parent()).val();
//alert(product);
var width = $(".width", $(this).parent().parent()).val();
var drop = $(".drop", $(this).parent().parent()).val();
var sub_total = $(".total", $(this).parent().parent());
if (product === "" || width === "" || drop === "") {
var parent = sub_total.val(0);
}
if (product !== "" && width !== "" && drop !== "") {
$.ajax({
url: "#",
method: "POST",
data: {
"product": product,
"width": width,
"drop": drop
},
success: function (data) {
if (data === "") {
var parent = sub_total.val(0);
}
else {
var parent = sub_total.val(data);
}
calculate(parent);
}
});
}
});

Related

Range slider filter with pure javascript by adding a function to my array.prototype

I have a table populated with animals and need to filter them by population and i want to use a range slider to filter them without using jQuery, just plain javascript, already have 2 filters using array.prototype. Here is my html code:
<fieldset>
<legend>Search by population</legend>
<input id="populationSlider" class="range-slider__range" type="range" value="100" min="194" max="500000" onchange="updateSliderNumber('populationNumber', this.value);">
<input id="populationNumber" type="number" value="100" min="194" max="500000" onchange="updateSliderNumber('populationSlider', this.value);">
<span class="range-slider__value"></span>
</fieldset>
and here is my sript:
(function(document) {
var AnimalFilter = (function(Arr) {
var _input;
var _select;
function _onInputEvent(e) {
_input = e.target;
var tables = document.getElementsByClassName(_input.getAttribute('data-table'));
Arr.forEach.call(tables, function(table) {
Arr.forEach.call(table.tBodies, function(tbody) {
Arr.forEach.call(tbody.rows, _filter);
});
});
}
function _onSelectEvent(e) {
_select = e.target;
var tables = document.getElementsByClassName(_select.getAttribute('data-table'));
Arr.forEach.call(tables, function(table) {
Arr.forEach.call(table.tBodies, function(tbody) {
Arr.forEach.call(tbody.rows, _filterSelect);
});
});
}
function _filter(row) {
var text = row.textContent.toLowerCase(), val = _input.value.toLowerCase();
row.style.display = text.indexOf(val) === -1 ? 'none' : 'table-row';
}
function _filterSelect(row) {
var text_select = row.textContent.toLowerCase(), val_select = _select.options[_select.selectedIndex].value.toLowerCase();
row.style.display = text_select.indexOf(val_select) === -1 ? 'none' : 'table-row';
}
return {
init: function() {
var inputs = document.getElementsByClassName('table-filter');
var selects = document.getElementsByClassName('select-table-filter');
Arr.forEach.call(inputs, function(input) {
input.oninput = _onInputEvent;
});
Arr.forEach.call(selects, function(select) {
select.onchange = _onSelectEvent;
});
}
};
})(Array.prototype);
document.addEventListener('readystatechange', function() {
if (document.readyState === 'complete') {
AnimalFilter.init();
}
});
})(document);
// Range-slider
function updateSliderNumber(id, value){
document.getElementById(id).value = value;
}
Ant suggestions?Do i need to call another function, or extend my prototype.array?
Thank you in advance!

Incorrect values are passed on click

On click of a button the code will check that "select all" is selected or individually selected. Now the problem is if one selects any "select all" checkbox and if then unchecked any option, then these unchecked values are passed instead of checked ones.
$("#next").click(function () {
debugger
$(".show").show();
$("#next").hide();
if ($('.checkbox2 ul.dropdown-content li input[type=checkbox]').first().is(':checked') == true){
$.each(budata, function (key, value) {
arr.push(key);
});
}else {
debugger
arr = $('option[name=BU]:checked').map(function () {
return this.value;
}).get();
}
var bu = arr.join(',');
HTML CODE
<div class="checkbox2">
<div class="input-field col s6">
<select id="dropdown1" multiple>
<option value="" disabled selected>Select BU</option>
</select>
<label>BU</label>
</div>
</div>
AJAX CALl for BU values(Checkbox values)
var data = {};
data.dateFrom = $("#dateFrom").val();
data.BU = $("#dropdown1").val();
data.Location = $("#Location").val();
data.Type = $("#dropdown").val();
$.ajax({
type: 'POST',
url: ServiceURL + 'MaterialClearance/getBU/',
async: false,
success: function (data) {
$('#dropdown1').html('<option id="selectall" name="selectall" value="selectall" ">(Select All)</option>');
if (data.length > 0) {
for (i = 0; i < data.length; i++) {
budata[data[i].BU] = 0;
$('#dropdown1').append('<option name="BU" value="' + data[i].BU + '">' + data[i].BU + '</option>')
}
}
$('#dropdown1').material_select();
}
});
CODE for select all nd individual checked checkbox
$('.checkbox2 ul.dropdown-content li').click(function () {
debugger
if ($('.checkbox2 ul.dropdown-content li').first().is(".selected")) {
$('.checkbox2 ul.dropdown-content li:not(:first-child)').each(function (index) {
$(this).find("input[type=checkbox]").prop("checked", $('.checkbox2 ul.dropdown-content li').first().find("input[type=checkbox]").prop("checked"));
});
}
else {
alert($('option[name=BU]:checked'));
$('.checkbox2 ul.dropdown-content li input[type=checkbox]').first().prop("checked", false);
alert($('option[name=BU]:checked'));
}
});

How to change the order of elements in listbox and store the values of listbox into an array using javascript

My listbox(MySelectLinks) is fetching values(AllLinks) from javascript array of objects stored in sharepoint list column.My listbox displays values of AllLinks:
[{"AllLinks":"abc","Order":7},{"AllLinks":"ghj","Order":9},{"AllLinks":"abcb","Order":4},{"AllLinks":"ghjnn","Order":1}]
I want to change the order by moving elements up and down and save this new order in array.So that the new order can be saved in list.
The following code changes the order but value cant be retained:
function MoveUp(lst){
if(lst.selectedIndex == -1)
alert('Please select an Item to move up.');
else
{
if(lst.selectedIndex == 0)
{
alert('First element cannot be moved up');
return false
}
else
{
var tempValue = lst.options[lst.selectedIndex].value;
var tempIndex = lst.selectedIndex-1;
lst.options[lst.selectedIndex].value = lst.options[lst.selectedIndex-1].value;
lst.options[lst.selectedIndex-1].value = tempValue;
var tempText = lst.options[lst.selectedIndex].text;
lst.options[lst.selectedIndex].text = lst.options[lst.selectedIndex-1].text;
lst.options[lst.selectedIndex-1].text = tempText;
lst.selectedIndex = tempIndex;
}} return false;}
Code to display values inside listbox:
function populateMyLinks()
{
$.ajax({
url: url,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data)
{
var blah = JSON.parse(data.d.results[0].AllLinks);
blah = sortJSON(blah, 'Order');
$.each(blah,function(i,result)
{
option2 += "<option value='" + result.AllLinks+"'>"+result.AllLinks+"</option>"
})
$("#MySelectLinks").append(option2);
},
error: function (data)
{
alert(data.responseJSON.error);
}
});
}
I didn't have time to add some comments to the code but I hope it pretty much explains itself. I hope it does what you're expecting it to do.
/* === ELEMENT MANIPULATION === */
function moveOptionDown(selectElement) {
const
optionElement = selectElement.options[selectElement.selectedIndex],
nextOption = selectElement.options[selectElement.selectedIndex + 1];
nextOption.insertAdjacentElement('afterend', optionElement);
}
function moveOptionUp(selectElement) {
const
optionElement = selectElement.options[selectElement.selectedIndex],
previousOption = selectElement.options[selectElement.selectedIndex - 1];
selectElement.insertBefore(optionElement, previousOption);
}
/* === ELEMENT MANIPULATION === */
/* === ARRAY METHODS === */
function generateOptionArray(selectElement) {
const
options = selectElement.options,
result = [];
for (var index=0; index < options.length; index++) {
result.push({
AllLinks: options[index].textContent,
Order: index
});
}
return result;
}
/* === ARRAY METHODS === */
/* === EVENT HANDLERS === */
function onMoveOptionUp(event) {
const
selectElement = document.getElementById('mySelect');
if (
selectElement.selectedIndex <= 0
) {
console.log('No option, or the first option, is selected. There is nothing to move');
return;
}
moveOptionUp(selectElement);
const
optionsArray = generateOptionArray(selectElement);
console.log(optionsArray);
}
function onMoveOptionDown(event) {
const
selectElement = document.getElementById('mySelect');
if (
selectElement.selectedIndex === -1 ||
selectElement.selectedIndex >= (selectElement.options.length - 1)
) {
console.log('No option, or the last option, is selected. There is nothing to move');
return;
}
moveOptionDown(selectElement);
const
optionsArray = generateOptionArray(selectElement);
console.log(optionsArray);
}
/* === EVENT HANDLERS === */
const
buttonUp = document.getElementById('move-up'),
buttonDown = document.getElementById('move-down');
buttonUp.addEventListener('click', onMoveOptionUp);
buttonDown.addEventListener('click', onMoveOptionDown);
<select id="mySelect">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
<option value="5">Option 5</option>
<option value="6">Option 6</option>
<option value="7">Option 7</option>
</select>
<button type="button" id="move-up">move selected element up</button>
<button type="button" id="move-down">move selected element down</button>

How will i prevent duplication of value and empty value

How can I prevent duplicate values being added to a combobox? I also need to prevent the space value. This is my code but its not working.
An entry is entered the first time input but the second time I enter input its alerting me that I have entered a duplicate value even when I enter different values.
Please see this jsFiddle https://jsfiddle.net/adLxoakv/
<HTML>
<HEAD>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<fieldset>
<legend>Combo box</legend>
Add to Combo: <input type="text" name="txtCombo" id="txtCombo"/>
Selected: <input type="text" name="selected" id="selected"/>
IMEI Selected: <input type="text" name="imei" id="imei"/>
<input type="button" id="button" value="Add" onclick="addCombo()">
<br/>
Combobox: <select name="combo" multiple id="combo"></select>
</fieldset>
</BODY>
</HTML>
<script>
$("#txtCombo").on("keydown", function (e) {
return e.which !== 32;
});
$(document).ready(function() {
$('#button').click(function(){
var data = [];
$.each($("#combo option:selected"), function() {
data.push($(this).attr("value"));
});
$('#imei').val(data.join(","));;
var count = $("#combo :selected").length;
$('#selected').val(count);
});
});
$("#combo").on('change', function () {
var count = $("#combo :selected").length;
$('#selected').val(count);
});
var text = $("#text").val();
function addCombo() {
var textb = document.getElementById("txtCombo");
var combo = document.getElementById("combo");
var option = document.createElement("option");
option.text = textb.value;
option.value = textb.value;
option.selected = true;
if (textb.length == 0) {
return false;
}
if (combo.length) {
alert("Duplicate found");
return false;
}
try {
combo.add(option, null ); //Standard
}catch(error) {
combo.add(option); // IE only
}
textb.value = "";
}
// separated by comma to textbox
$(document).ready(function() {
$("#combo").change(function() {
var data = [];
$.each($("#combo option:selected"), function() {
data.push($(this).attr("value"));
});
$('#imei').val(data.join(","));;
});
});
</script>
To find the duplicate you can use following function(using jQuery)
function isDuplicate(value,text){
/*Get text of the option identified by given value form the combobox and then check if its text matches the given text*/
if($('#combo select option[value="' + value + '"]').text() == text)
return true;
else
return false;
}
Update:
function addCombo() {
var textb = document.getElementById("txtCombo");
var combo = document.getElementById("combo");
var option = document.createElement("option");
var value = textb.value.trim();
option.text = value;
option.value = value;
option.selected = true;
if (textb.length == 0) {
return false;
}
if ($('#combo option[value="' + value + '"]').text() == value ) {
alert("Duplicate found");
return false;
}
try {
combo.add(option, null ); //Standard
}catch(error) {
combo.add(option); // IE only
}
textb.value = "";
}

Object function work first time but return undefined the second time

My code works fine for the first time but the second time, my object functions returns undefined.
_MANAGE = new Object()
//----------------------------- BG ------------------------------//
var saveBg = {
name : "bg",
url : "AN URL",
data : {
ID :function($this){ return $this.parents("tr").data("id") },
name :function($this){ return $this.parents("tr").find(".name").val() }
}
}
//----------------------------------------------------------------------//
//------------------------- SAVE FUNCTION ------------------------------//
var saveButton = [saveBg];
$(".buttonSave").on("click", function(){
console.log(saveBg);
var buttonName = $(this).data("name");
_MANAGE.saveButton(saveButton, buttonName, $(this));
})
//----------------------------------------------------------------------//
//------------------------- SAVE BUTTON ------------------------------//
_MANAGE.saveButton = function(saveButton, buttonName, $this_button){
for(var i = 0; i < saveButton.length; i++){
if(buttonName == saveButton[i]["name"]){
for(var param in saveButton[i]["data"]){
if(typeof(saveButton[i]["data"][param]) == "function"){
saveButton[i]["data"][param] = saveButton[i]["data"][param]($this_button);
} else {
saveButton[i]["data"][param] = $(saveButton[i]["data"][param]).val();
}
}
if(!saveButton[i]["success"]){
saveButton[i]["success"] = function() {
$this_button.children()
.hide()
.replaceWith("<span style='font-size:0.7em;''>Saved</span>").fadeIn("slow");
setInterval(function(){
$this_button.children().hide().replaceWith('<span class="icon-floppy"> </span>').fadeIn("slow");
}, 1500);
}
}
_MANAGE.ajaxButton(saveButton[i]);
}
}
}
//----------------------------------------------------------------------//
//------------------------- ASYNC FUNCTION ------------------------------//
_MANAGE.ajaxButton = function(ajaxButton) {
var stringData = "";
if(ajaxButton.data){
var loop = 0;
for(var param in ajaxButton["data"]){
if(loop == 0){
stringData += param + "=" + ajaxButton["data"][param];
} else {
stringData += "&" + param + "=" + ajaxButton["data"][param];
}
loop++;
}
}
if(ajaxButton.url && ajaxButton.success && stringData != "") {
$.ajax({
url : ajaxButton.url,
data : stringData,
dataType : "text",
success : ajaxButton.success
});
}
}
<!--THE TABLE -->
<tr data-id="4">
<td><b>4</b></td>
<td><input class="name" type="text" value="A VALUE"></td>
<td>
<!-- THE BUTTON -->
<div class="buttonSave" data-name="bg">
<span class="icon-floppy"></span>
</div>
</td>
</tr>

Categories