JQuery - Get value after delimiter alternative? - javascript

I've already searched this up before and tried using both pop() and lastIndexOf but it doesn't work well on looped dropdown.
Is there any alternative to getting the value after a delimiter, one that does not remove it from the list?
Here's my code:
$(document).ready(function () {
$('#VehicleID').change(function () {
var vehdrv = ($('#VehicleID :selected').val());
var drvid = vehdrv.split("_").pop();
var vehid = vehdrv.split("_")[0];
$('#VehicleID :selected').val(vehid);
//alert($('#VehicleID :selected').val());
if (drvid > 0) {
$('#DriverID').find("option").show().not("option[value*='" + drvid + "']").hide();
$("#DriverID").val(drvid);
//$("#DriverID").val(
//$("#DriverID").find("option:visible:first").val())
}
else {
$("#DriverID").find("option").show();
$("#DriverID").val(
$("#DriverID").find("option:visible:first").val())
}
}).trigger("change");
})
My Dropdowns from the controller:
public ActionResult ReserveInitial()
{
ViewBag.VehicleID = db.Vehicles.Where(item => item.IsReserved == false).Select(a => new SelectListItem
{
Value = a.VehicleID.ToString() + "_" + a.DriverID.ToString(),
Text = a.VehicleMake + " - " + a.PlateNumber,
});
ViewBag.DriverID = db.Drivers.Select(a => new SelectListItem
{
Value = a.DriverID.ToString(),
Text = a.DriverLastName + ", " + a.DriverFirstName
});
return View();
}
EDIT
This is how the string would look like if the VehicleID is linked to a Driver:
"14_5"
if the VehicleID is not associated with a Driver it would look like this:
"15_0"

var parts = vehdrv.split("_");
var drvid = parts[1];
var vehid = parts[0];

You can try this
var vehdrv = $('#VehicleID').val().match(/[^_]+/g);
var drvid = vehdrv[0];
var vehid = vehdrv[1];
console.log(drvid,vehid);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="VehicleID" type="text" value="14_5" name="text">

Related

How to pass a JavaScript variable to XML?

I want to pass JavaScript variable's value to an XML file. I have already seen this question and answer here but since my XML file is not that small but rather big, I would like to know how to do this without writing whole xml if possible.
I have this JavaScript code
render_receipt: function () {
// this._super();
var self = this;
if (self.pos.config.disable_fiscalization == false) {
var data = self.get_receipt_render_env();
self.$('.pos-receipt-container').html("")
var total_amount = data['receipt']['total_with_tax'];
var vat = self.pos['company']['vat'];
var header_time = data['order']['formatted_validation_date'];
var order_name = data['order']['name'];
var soft_code = self.pos['company']['software_code'];
var business_unit_code = self.pos['config']['business_unit_code'];
var business_unit_address = self.pos.business_unit_address
var tcr_code = self.pos['config']['tcr_code'];
var operator_code = self.pos.get_cashier().operator_code
// create message
message = vat + '|' + header_time + '|' + order_name + '|' + business_unit_code + '|' + tcr_code + '|' + soft_code + '|' + total_amount
var order = self.pos.get_order();
if (!this.pos.config.iface_print_via_proxy) {
var invoiced = new $.Deferred();
// if (self.pos.config.disable_fiscalization == false) {
// console.log("hasEnoughSpeed", hasEnoughSpeed, isAlive)
if (isAlive && hasEnoughSpeed) {
rpc.query({
model: 'pos.order',
method: 'search_read',
domain: [['pos_reference', '=', order['name']]],
fields: ['iic_code', 'header_send_datetime', 'amount_total', 'fic', 'business_unit_code', 'operator_code', 'fiscalization_url', 'partner_id']
})
.then(function (orders) {
var partner = null;
if (orders.length && orders[0]['partner_id'] == false) {
var data = self.get_receipt_render_env();
data['partner_name'] = orders[0]['partner_id'][1];
data['street'] = false;
data['country'] = false;
data['city'] = false;
data['zip'] = false;
data['vat'] = false;
data['nslf'] = orders[0]['iic_code'];
// alert(data['nslf'])
data['nivf'] = orders[0]['fic'];
data['business_unit_code'] = business_unit_code;
data['operator_code'] = operator_code;
data['business_unit_address'] = business_unit_address
self.$('.pos-receipt-container').html(qweb.render('PosTicket', data));
var qr = new QRious({
element: document.getElementById('qr-code'),
size: 200,
});
I'd like to pass data['nsfl'] to this XML div tag. I have already tried as you see and it is failing, I get why it is failing and from the other side I don't know how to make work either. Thanks in advance guys!!!
<div>
<div style="font-weight:bold;font-size:12px;">NSLF: <t t-esc="data['nslf']"/></div>
</div>

How to remove existing values from an Array?

In this script I select checked id and store string in hidden field.
For removing exist id I have stored string in array.
I want to remove exist id from array and store array values into
hidden field.
Script:
AddRemoveCustomer = function(){
$(".checkBoxClass").click(function (e) {
//var CustomerIDArray = '';
var hidCID = document.getElementById("hfCustomerID");
var CustArray = [];
if(hidCID!=null || hidCID!=undefined)
{
var CustID = hidCID.value;
CustArray = CustID.split("");
alert('CustID is :' + CustID );
alert('CustArray is :' + CustArray );
if (CustID == null || CustID=="") {
$(".checkBoxClass:checked").each(function () {
alert("Null");
//CustomerIDArray = $(this).val();
//alert(CustomerIDArray);
alert('value : '+$(this).val());
hidCID.value = $(this).val();
});
} else {
alert("Not Null");
//CustomerIDArray = CustID;
$(".checkBoxClass:checked").each(function () {
alert($(this).val());
//CustomerIDArray = CustomerIDArray + "," + $(this).val();
//alert(CustomerIDArray);
CustID = CustID +","+ $(this).val();
alert(CustID);
alert('value : '+$(this).val());
hidCID.value = CustID;
});
}
//CustID = CustomerIDArray.values;
}
//$('#hfCustomerID').val(allSelectedValues);
//alert($('#hfCustomerID').val());
});
};
To remove array item use Array.splice(startIndex, deleteCount).
let elIndex = custArray.indexOf(deleteId);
custArray.splice(elIndex, 1);

Setting variable through external method in method of object

I am using the method of a javascript object to create HTML to write that object.
Within that method I have a date (in string format as a SQL Date) which I format to dd MMM YYYY in an external method. The external method works fine returning the string I need, but when I set the variable within my object's method it is returned as undefined.
Hereby the relevant code:
function CreateReview(reviewID, visitDate) {
var reviewObject = {
iD: reviewID,
visitDate: visitDate,
CreateReviewObject : function(c) {
var reviewContainer = document.createElement('div');
reviewContainer.id = 'Review_' + this.iD;
reviewContainer.className = 'Card Review';
var headerDIV = document.createElement('div');
headerDIV.className = 'Header';
var dateTagsDIV = document.createElement('div');
dateTagsDIV.className = 'DateTags';
var datesDIV = document.createElement('div');
datesDIV.className = 'Dates';
var formattedVisitDate = getFormattedDate(this.visitDate);
console.log(formattedVisitDate);
var dateDIV = document.createElement('div');
dateDIV.className = 'Date';
dateDIV.innerHTML = formattedVisitDate;
datesDIV.appendChild(dateDIV);
dateTagsDIV.appendChild(datesDIV);
headerDIV.appendChild(dateTagsDIV);
reviewContainer.appendChild(headerDIV);
return reviewContainer;
}
};
return reviewObject;
}
function getFormattedDate(input) {
input = input.replace(/-/g,'/');
var pattern = /(.*?)\/(.*?)\/(.*?)$/;
var result = input.replace(pattern,function(match,p1,p2,p3){
p2 = parseInt(p2);
p3 = parseInt(p3);
var months = ['jan','feb','maa','apr','mei','jun','jul','aug','sep','okt','nov','dec'];
var date = (p3<10?"0"+p3:p3) + " " + months[parseInt(p2-1)] + " " + p1;
console.log(date);
return date;
});
}
The output of the console in getFormattedDate is then
12 mei 2015
While in CreateReview it is
undefined
I have tried the following way as well:
function CreateReview(reviewID, restaurant, kitchenTypes, tags, pictures, ratings, thumbPicture, visitDate, introduction, description) {
var reviewObject = {
iD: reviewID,
visitDate: visitDate,
CreateReviewObject : function(c) {
var getFormattedVisitDate = function(visitDate) {
return function() { getFormattedDate(visitDate); };
};
var reviewContainer = document.createElement('div');
reviewContainer.id = 'Review_' + this.iD;
reviewContainer.className = 'Card Review';
var headerDIV = document.createElement('div');
headerDIV.className = 'Header';
var dateTagsDIV = document.createElement('div');
dateTagsDIV.className = 'DateTags';
var datesDIV = document.createElement('div');
datesDIV.className = 'Dates';
var formattedVisitDate = getFormattedVisitDate(this.visitDate);
console.log(formattedVisitDate);
var dateDIV = document.createElement('div');
dateDIV.className = 'Date';
dateDIV.innerHTML = formattedVisitDate;
datesDIV.appendChild(dateDIV);
dateTagsDIV.appendChild(datesDIV);
headerDIV.appendChild(dateTagsDIV);
reviewContainer.appendChild(headerDIV);
return reviewContainer;
}
};
return reviewObject;
}
function getFormattedDate(input) {
input = input.replace(/-/g,'/');
var pattern = /(.*?)\/(.*?)\/(.*?)$/;
var result = input.replace(pattern,function(match,p1,p2,p3){
p2 = parseInt(p2);
p3 = parseInt(p3);
var months = ['jan','feb','maa','apr','mei','jun','jul','aug','sep','okt','nov','dec'];
var date = (p3<10?"0"+p3:p3) + " " + months[parseInt(p2-1)] + " " + p1;
console.log(date);
return date;
});
}
Which gives me this output in in CreateReview:
return function() { getFormattedDate(visitDate); };
Why does the CreateReview call return undefined when the console does not?
In your function getFormattedDate(), you have
var result = input.replace(pattern, function(match,p1,p2,p3) {... return date; });
so result contains the returned value of the replace function, but getFormattedDate doesn't return anything ==> undefined when called from CreateReview.
Add return result; at the end of the function getFormattedDate.

Splitting out xml result into dropdownlist

Hope someone can help - I'm new to js/jQuery so I'm hoping it's something really simple I'm missing here.
I'm trying to populate a dropdownlist with the xml result from below. The parseXML function works great and the result.push(valueid + "," + value) leaves me with the following:
1,Service
2,Breakdown
How do I get this into a dropdownlist please? Using the below, I get the error "Object doesn't support property or method 'split'"
Many thanks
leddy
function testFunction() {
var jobresults = "<resultset morerecords='0'> " +
"<result> " +
"<itt_jobtypeid>1</itt_jobtypeid> " +
"<itt_name>Service</itt_name> " +
"</result> " +
"<result> " +
"<itt_jobtypeid>2</itt_jobtypeid> " +
"<itt_name>Breakdown</itt_name> " +
"</result> " +
"</resultset> ";
var xml = parseXML(jobresults);
var jobid = xml.getElementsByTagName("itt_jobtypeid");
var jobname = xml.getElementsByTagName("itt_name");
var result = [];
for (var i = 0; i < jobid.length; i++) {
var valueid = jobid[i].childNodes[0].nodeValue;
var value = jobname[i].childNodes[0].nodeValue;
// add longitude value to "result" array
result.push(valueid + "," + value);
}
var jobtype = $("#ddlJobType");
$.each(result, function () {
var arr = result.split(',');
for (var i = 0; i < arr.length; i++) {
jobtype.append($("<option />").val(arr[0]).text(arr[1]));
}
});
}
function parseXML(text) {
if (window.DOMParser) {
parser = new DOMParser();
doc = parser.parseFromString(text, "text/xml");
}
else { // Internet Explorer
doc = new ActiveXObject("Microsoft.XMLDOM");
doc.async = "false";
doc.loadXML(text);
}
return doc;
}
It can be simpler and cleaner if you optimize data structure for result array. Push an object with value and label so that you can simply use attr method directly after:
for (var i = 0; i < jobid.length; i++) {
var valueid = jobid[i].childNodes[0].nodeValue;
var value = jobname[i].childNodes[0].nodeValue;
// add longitude value to "result" array
result.push({value: valueid, label: value});
}
var jobtype = $("#ddlJobType");
$.each(result, function (i, obj) {
$('<option>').attr(obj).appendTo(jobtype);
});
See https://api.jquery.com/jquery.each/. The callback function gets each jobtype as parameter to the function.
Try changing the code to:
$.each(result, function (idx, value) {
var arr = value.split(',');
for (var i = 0; i < arr.length; i++) {
jobtype.append($("<option />").val(arr[0]).text(arr[1]));
}
});

How can i use multiple pagedown in one page?

I tried the below code for that, but it adds pagedown buttons to only the first .wmd-input.
if ($(".wmd-input").length > 0) {
var converter = new Markdown.Converter();
var help = function () { alert("Do you need help?"); }
var options = {
helpButton: { handler: help },
strings: {quoteexample: "whatever you're quoting, put it right here"}
};
var editors = [];
var i = 0;
$(".wmd-input").each(function() {
editors[i] = new Markdown.Editor(converter, "", options);
editors[i].run();
i = i + 1;
});
}
Looks like i have to add unique ID for each element of wmd. I mean wmd-input, wmd-preview and wmd-button-bar. I modified this id attributes programmatically. This can be done with modifying manually but my length of inputs are dynamic.
// make wmd's id's unique
var pBox = $(this).parents(".box");
$(pBox).find("textarea").attr('id', "wmd-input" + i);
$(pBox).children("#wmd-preview").attr('id', "wmd-preview" + i);
$(pBox).find("#wmd-button-bar").attr('id', "wmd-button-bar" + i);
So when this ID attributes is set, i called the editor with postfix variable and problem solved.
editors[i] = new Markdown.Editor(converters[i], i, options);
if ($(".wmd-input").length > 0) {
var converters = [];
var editors = [];
var i = 1;
$(".wmd-input").each(function() {
converters[i] = new Markdown.Converter();
var help = function () { alert("Do you need help?"); }
var options = {
helpButton: { handler: help },
strings: {quoteexample: "whatever you're quoting, put it right here"}
};
// make wmd's id's unique
var pBox = $(this).parents(".box");
$(pBox).find("textarea").attr('id', "wmd-input" + i);
$(pBox).children("#wmd-preview").attr('id', "wmd-preview" + i);
$(pBox).find("#wmd-button-bar").attr('id', "wmd-button-bar" + i);
editors[i] = new Markdown.Editor(converters[i], i, options);
editors[i].run();
i = i + 1;
});
}

Categories