change text to input and back to text - javascript

I have a product list, price is normal text. When I click in with price, I want to replace text by input and when I call the blur event, it update DB data and replace input by text.
I have this code:
<td>
<span onclick="make_field(this, 'text', '11', '12,350.00')">12,350.00</span> €
</td>
<script>
function make_field(el, type, id, val) {
var el = $(el);
el.html('<input onblur="update_db_row(params); make_el(this, \'span\', ' + id + ', \'' + val + '\', \'' + **this.value** + '\')" type=' + type + ' name=' + id + ' value="' + val.replace(',',' ').replace(',',' ').replace('.',',') + '">'); // replace 12,350.00 to 12350,00
el.attr('onclick', '');
}
function make_el(el, tag_name, id, old_value, **new_value**) {
var el = $(el);
alert(old_value);
alert(new_value); // undefined, how I can give current input value to function when I click outside the input?
}
</script>
Thanks.

I believe this is what you want: jsFiddle example
You can obtain the new value directly from the input element, as follows:
function make_field(el, type, id, val) {
var el = $(el);
el.html('<input onblur="update_db_row(); make_el(this, \'span\', ' + id + ', \'' + val + '\')" type=' + type + ' name=' + id + ' value="' + val.replace(',', ' ').replace(',', ' ').replace('.', ',') + '">'); // replace 12,350.00 to 12350,00
el.attr('onclick', '');
}
function make_el(el, tag_name, id, old_value) {
var el = $(el);
// Get the new value directly from the input.
var new_value = el.val();
// Set the new value on the span and remove the input box.
el.parent().html(new_value);
el.remove();
}
function update_db_row() {}

Related

How to get specific value from option select - json object

I am trying to extract data from the option value. For example only ID or UserName. Can you please help?
$(document).ready(function() {
$.getJSON("http://localhost:8080/EBCargoAndCommodityServices/resources/user-form/retrieve", function(data) {
data.forEach(function(dt) {
$("#customer-list").append('<option value="' + dt.id + dt.contactName + '">' + dt.contactName + '</option>');
});
$('#customer-list').change(function() {
var str = this.value;
alert(str);
});
});
});
Let's say for example that dt.id = 1 and dt.contactName is Bartosz.
So you would be alerting 1Bartosz in alert(str)
While building up the options do this,
$("#customer-list").append('<option value="' + `${dt.id}_${dt.contactName}` + '">' + dt.contactName + '</option>'); // Using template literals and concatenating both id and contact name using a delimiter `_`
Then, in your change function do this.
const info = str.split('_')
/*
info will be an array with two elements
info[0] will be id i.e. 1
info[1] will be contactName i.e. Bartosz
*/
Sure you can, the best way would be to store the values you need to use into specific data attributes, then access them using the .data() method
const $ = jQuery;
$(document).ready(function() {
// Mocked data for test
const data = [{"address":"","companyName":"","contactName":"ghkkkkk","email":"","id":22,"surname":"","telephone":0},
{"address":"","companyName":"","contactName":"asdasd","email":"","id":23,"surname":"","telephone":0}]
data.forEach(function(dt) {
$("#customer-list").append('<option data-id="' + dt.id + '" data-name="' + dt.contactName + '" value="' + dt.id + dt.contactName + '">' + dt.contactName + '</option>');
});
$('#customer-list').change(function() {
const selected = $(this).find('option:selected');
$('#result').text('selected id is: ' + selected.data('id') + ' contact name is : ' + selected.data('name'))
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="customer-list">
<option>select an option</option>
</select>
<span id="result"></span>

How can i use dynamic variables names in my jquery function

I am just learning jquery and javascript and i have a function that unwraps [select] elements on my page and displays them as buttons. There could be multiple select boxes on my page so I need to dynanically name the following variables based on the elementname that is passed in, so that when the buttons are clicked it passed the correct values:
selector1
currentvalue1
hidden1
svalue1
This is the function:
function doUnwrap(elementname) {
var selector1 = document.getElementById('' + elementname + '');
var currentvalue1 = selector1[selector1.selectedIndex].text;
var hidden1 = $('<input type="hidden" name="' + elementname + '">');
hidden1.val($('[name=' + elementname + ']').val());
hidden1.insertAfter($('[name=' + elementname + ']'));
$("[name=" + elementname + "] option").unwrap().each(function () {
var btn = $('<div class="btn" id="' + $(this).attr('value') + '">' + $(this).text() + '</div>');
if ($(this).text() == currentvalue[i]) {
var btn = $('<div class="btn" id="' + $(this).attr('value') + '" >' + $(this).text() + '</div>');
if ($(this).is(':checked')) btn.addClass('on');
$(this).replaceWith(btn);
} else {
var btn = $('<div class="btn" id="' + $(this).attr('value') + '" >' + $(this).text() + '</div>');
$(this).replaceWith(btn);
};
});
$(document).on('click', '.btn', function () {
$('.btn').removeClass('on');
$(this).addClass('on');
$('input[name=' + elementname + ']').val($(this).text());
var sValue1 = "&value=" + elementname + "|" + $(this).attr('id') + "";
executeAjaxEvent(sValue1, null, "ComboBoxAjaxHandler", false, null, true);
});
}

jquery - add event listener to dynamically created button

I've tried multiple solutions but none worked and I don't understand why...
Basically, I have a button that appends a new form line into my page, with name, start and colour fields and a save button.
What I need to do is save the form fields on save click.
Here's the code I'm trying to use but it's not working:
var i = 0;
var addCounter = $("#addCounter");
addCounter.on("click", function () {
++i;
var body = $("body");
var save = $('#save-' + i);
var name = $("#counterName-" + i);
var date = $("#counterStart-" + i);
var color = $("#counterColor-" + i);
var status = $("#status-" + i);
var templateToAppend = '<li class="list-group-item">' +
'<div class="form-inline">' +
'<div class="form-group">' +
'<label for="counterName-' + i + '">Counter Name</label>' +
'<input type="text" id="counterName-' + i + '" placeholder="Counter name"/></div>' +
'<div class="form-group">' +
'<label for="counterStart-' + i + '">Starting from:</label>' +
'<input type="text" id="counterStart-' + i + '" placeholder="dd/mm/yy"/></div>' +
'<div class="form-group">' +
'<label for="counterColor-' + i + '">Counter Color:</label>' +
'<input id="counterColor-' + i + '" class="jscolor"></div>' +
'<button id="save-' + i + '" class="btn btn-primary">Save</button>' +
'<div id="status-' + i + '"></div></div></li>';
body.append(templateToAppend);
save.click(function () {
debugger;
console.log("clicked on save: ", save);
var localStorage = {
id: i,
counterName: name.value,
counterDate: date.value,
counterColor: color.value
};
console.log(localStorage);
});
});
the debugger never runs and I don't understand why.
Can you please help me understand why?
thanks a lot
Well that is because you have tried to create jquery object of element which is not there in DOM. You should append the element first and then get element by selector. Like this:
body.append(templateToAppend);
var save = $('#save-' + i);
var name = $("#counterName-" + i);
var date = $("#counterStart-" + i);
var color = $("#counterColor-" + i);
var status = $("#status-" + i);
also there is much cleaner way to attach event to dynamically added element. Have a look at Event Delegation
var save = $('#save-' + i);
This line of code is executing before the button is added to the document.
save will be an empty array.
Use event delegation for you second click event,place the click event outside the first click event
$('body').on('click','.list-group-item btn',function () {
console.log("clicked on save: ", $(this).attr('id'));
var i = $(this).attr('id').split('-')[1];
var localStorage = {
id: i,
counterName: $("#counterName-" + i).val(),
counterDate: $("#counterStart-" + i).val(),
counterColor: $("#counterColor-" + i).val()
};
console.log(localStorage);
});

jQuery returns [object HTMLInputElement] instead of string from .val()

I am using jQuery to generate some input fields and buttons on the fly. I provide an ID attributes for these elements, which are also dynamically generated using an algorithm:
// Where menuItem is a string (ex. 'Child Admission' -> 'Child_AdmissionQuantity')
var quantityId = menuItem.replace(' ', '_') + 'Quantity';
I then use the same algorithm to select the field using jQuery and attempt to get the value of the input field:
// Get Reference to the quantity field
var quantityId = '#' + menuItem.replace(' ', '_') + 'Quantity';
console.log("quantityId: " + quantityId);
// Get the Value of the field
var quantity = $(quantityId).val();
Instead of returning a string, jQuery returns a [object HTMLInputElement].
Here is how I create the form fields:
function processMenuItem(menuItem) {
// Generate a quantityId
var quantityId = menuItem.replace(' ', '_') + 'Quantity';
console.log("menuItem: " + menuItem + "\n"
+ "quantityId: " + quantityId + "\n");
// Generate a Menu Item Option
var menuItemOption = '<div class="product">'
+ '<div class="productName">' + menuItem + '</div>'
+ '<div class="quantity">'
+ '<input type="text" name="quantity" id="' + quantityId + '" placeholder="2" />'
+ '</div>'
+ '<button type="button" onclick="addItem(\'' + menuItem + '\')">Add Item</button>'
+ '</div><!-- End of .product -->';
// Add the Option to the Menu
$('#displayMenu').append(menuItemOption);
}
I need the actual value for form processing, anyone know a work around?
Thanks!

Filter JQuery list with URL

I need to modify some code already in place. There's a block of code that filters a JQuery list using the URL to populate the search input.
E.g.
http://***/store/mobile/page/productList.page?search=football
Automatically enters "football" in the search bar.
Now I'd need to filter the list, without using the search bar.
So lets say my URL would look something like this :
http://***/store/mobile/page/productList.page?football
This would filter the list with football without using the search bar.
Here's the code I need to change. Please tell me if my question is unclear.
$('div[data-url*="productList"]').live("pageshow", function() {
filterValue = getParameterByName("search", location.search);
if (filterValue) {
$('input[data-type="search"]').val(filterValue);
}
refreshList();
});
and:
$.each(catalog.products,
function(index, value) {
if ((!filterValue )
|| value.name.toUpperCase().indexOf(filterValue.toUpperCase()) != -1
|| value.brand.toUpperCase().indexOf(filterValue.toUpperCase()) != -1)
{
items.push('<li id="' + index + '">' +
'<a data-identity="productId" href="./details.page?productId=' + index + '" >' +
'<img class="ui-li-thumb" src="' + value.thumbnail + '"/>' +
'<p>' + value.brand + '</p>' +
'<h3>' + value.name + '</h3>' +
'<span class="ui-li-count">' + value.price + ' $</span></li>') +
'</a>';
}
});
if there will always be only 1 parameter after ? than you could simply get it from page location in javascript, e.g.
var url = document.location;
var params = url.split("?");
filterValue = params[params.length-1]
if (filterValue) {
$('input[data-type="search"]').val(filterValue);
}
refreshList();
example: http://jsfiddle.net/yPgPc/

Categories

Resources