I have this code below I just need to divide the string into parts in the onSelect parameter of auto complete function
$(function(){
$('#business_category').autoComplete({
minChars: 2,
source: function(term, response){
term = term.toLowerCase();
var countryName = $("select[name=country]").val();
var data_search_term = $("input[name=business_category]").val();
console.log(countryName);
$.ajax({
type: "POST",
url: "ajax/businesses_search_terms_count.php",
data: "countryName=" + countryName + "&searchTerm=" + data_search_term,
dataType: "json",
success: function(resp){
response(resp.data)
}
});
},
onSelect: function(event, term, item) {
console.log("searchedItem: " + term);
var data_search_term = $("input[name=business_category]").val();
$('#total-count').html(data_search_term);
}
});
});
Right now, when user selects any category my output is: (Audio and video => 6,488). But I want an output like this: (Audio and video). So I just want a string with the category field not with count number like => 6,488
As #Donny stated, you can achieve it with pure Javascript. My solution is very similar to his but I just wanted to share a little bit more concise solution using template strings:
const str = "(Audio and video => 6,488)";
console.log(`${str.split("=>")[0].trim()})`);
You can achieve your goal using pure JavaScript with string.split() and string.trim()
var str = "(Audio and video => 6,488)";
var res = str.split("=>")[0]; //Turn string into array splitting by '=>' and get the first element
res = res.trim(); //Remove side spaces
res += ')'; //add ')' to the end of the string
console.log(res); //prints to console '(Audio and video)'
Related
In Firebug net tab, in Response\Json tabs, I can see the value returned from CGI, using ajax:
I want to verify the exact characters values, so I can translate it into readable characters (and in the next step, store my values in the same encoding.)
How can I get this value in Javascript?
I tried to use encodeURI() on the ajax returned response, but I only got some [%EF%BF%BD] (the black-diamond-question-mark)
my JS code:
var jqxhr = $.ajax({
type: "GET",
url: AJAX_CGI_URL,
dataType : 'json',
cache: false,
data: { name: AJAX_PARAMS }
})
. . .
case "P_D":
for(var j = 0; j < varVal.length; j++) {
jj=j+1;
updateWidget("d" + jj, varVal[j]);
var res = encodeURI(varVal[j]);
console.log(jj + ": " + res);
} break;
=>
console log:
GET http://.../cgi-bin/xjgetvar.cgi ...
1: %EF%BF%BD%EF%BF%BD%EF%BF%BD%EF%BF%BD%20%EF%BF%BD%EF%BF%BD%EF%BF%BD
which is actually => %EF%BF%BD %EF%BF%BD %EF%BF%BD %EF%BF%BD %20 %EF%BF%BD %EF%BF%BD %EF%BF%BD
[relates to my previous question - JavaScript encodes Hebrew string
I thought it will be easy to get the values Firebug shows. but it is not trivial :( ]
so my question now is - How can I get the same values Firebug gets ?!
How can I get the array value from a hidden input field and be able to grab the elements I need?
<input type="hidden" name="digital_object[prdcls][0][prdcl_links][0][_resolved]" id="digital_object[prdcls][0][prdcl_links][0][_resolved]" value="{"id":"/prdcl_titles/1","title":"test (test)","primary_type":"prdcl_title","types":["prdcl_title"],"json":"{\"lock_version\":0,\"title\":\"test (test)\",\"publication\":\"test\",\"publisher\":\"test\",\"created_by\":\"admin\",\"last_modified_by\":\"admin\",\"create_time\":\"2016-06-07T13:20:46Z\",\"system_mtime\":\"2016-06-07T13:20:46Z\",\"user_mtime\":\"2016-06-07T13:20:46Z\",\"jsonmodel_type\":\"prdcl_title\",\"uri\":\"/prdcl_titles/1\"}","suppressed":false,"publish":false,"system_generated":false,"repository":"global","created_by":"admin","last_modified_by":"admin","user_mtime":"2016-06-07T13:20:46Z","system_mtime":"2016-06-07T13:20:46Z","create_time":"2016-06-07T13:20:46Z","uri":"/prdcl_titles/1","jsonmodel_type":"prdcl_title"}">
When I run this I get 'undefined' for valp.
I also have the issue where the function prdcl_link is not executing on the hidden field being created or changed.
$( document ).ready(function() {
$("#digital_object[prdcls][0][prdcl_links][0][_resolved]").on('keyup change', prdcl_link);
$("#digital_object_prdcls__0__volume_num_").on('keyup change', prdcl_link);
$("#digital_object_prdcls__0__issue_num_").on('keyup change', prdcl_link);
function prdcl_link(){
var valp = {};
valp = $("#digital_object[prdcls][0][prdcl_links][0][_resolved]").val();
console.log(valp);
var valv = $("#digital_object_prdcls__0__volume_num_").val();
var vali = $("#digital_object_prdcls__0__issue_num_").val();
var res;
var pub;
var vol;
var iss;
if (valp!=""){
pub = valp['json']['publication'];
res = pub;
if (valv!=""){
vol = " - Volume " + valv;
res = res.concat(vol);
}
if (vali!=""){
if (valv!=""){
iss = ", Issue " + vali;
}
else {
iss = " - Issue " + vali;
}
res = res.concat(iss);
}
}
$("#digital_object_title_").val(res);
};
});
The value of the input seems to be JSON format, but HTML encoded. First you need to decode the string. Underscore have en unescape function, or you can search to find other ways to do it.
Then you can use JSON.parse to convert it to a javaScript object. But you have an error, so it can't be parsed. There are some extra quotes around an object named 'json'
...,"json":"{...}",...
If you didn't have the quotes around the brackets, it would be valid. What I think happened here is the 'json' object got converted to JSON format (a string) first. Then this string was part of another object, which also got converted to JSON. Now it's impossible to distinguish which quotes is part of what.
I have a string that looks like this
id = 'CourseContent1_activityContent34169_question1_answer0_ac';
Is there an easier way to increment the numbers at the end of "question1" and "answer0" inside of the string? I have tried to separate the contents of the string using the following method:
id = 'CourseContent1_activityContent34169_question1_answer0_ac';
idArray = id.split('_');
originalArray = idArray.slice();
if (idArray) {
idArray.pop();
for (i = 0; i < 2; i++) {
idArray.shift();
}
}
The above results in:
idArray = ["question1","answer0"];
but the final result needs to be a string, I know I'll probably need to concatenate it later, so I can pass it into another argument. I just need to isolate those two numbers and increment only those two. I was searching for an easier way to finish that task but I haven't come across anything like that. Also jQuery isn't an option for me since I'm trying to accomplish this using just javascript and the console. Thank you for your help in advance.
You can try this :
var id = 'CourseContent1_activityContent34169_question1_answer0_ac';
var incrementQuestion = function (id) {
return id.replace(/question([0-9]+)/, function (val1, val2) {
return "question" + (parseInt(val2) + 1)
}) }
var incrementAnswer = function (id) {
return id.replace(/answer([0-9]+)/, function (val1, val2) {
return "answer" + (parseInt(val2) + 1)
}) }
then increment using:
id = incrementAnswer(id);
and
id = incrementQuestion(id);
You can use regular expressions to find the string "question1" and replace it with "question2" - or more accurately "question{any number here}" and replace with "question{any other number}"
var id = 'CourseContent1_activityContent34169_question1_answer0_ac'
var re = /question\d+/
var id2 = id.replace(re,"question2")
You can do the same for answer\d+
You should use replace function of RegExp:
Please run the example below:
var id = 'CourseContent1_activityContent34169_question1_answer0_ac';
alert('before:\r' + id)
id = id.replace(/question([0-9]+).*answer([0-9]+)/, function(a, b, c) {
return 'question' + (parseInt(b) + 1) + '_answer' + (parseInt(c) + 1)
// Using parseInt to convert string to number
})
alert('after:\r' + id)
function updateQA(question, answer) {
return 'CourseContent1_activityContent34169_question1_answer0_ac'.replace(/^(.*question)(\d*)(_answer)(\d*)(.*)/gi, '$1' + question + '$3' + answer + '$5');
}
Here's a bit of a less verbose way of doing it:
var increment = function(_, prefix, n) { return prefix + (+n + 1) };
id.replace(/(question)(\d+)/, increment).replace(/(answer)(\d+)/, increment);
The parenthesized matches (i.e. the capturing groups) are passed as separate args to the replacement functions, and there you can just increment them and return with the corresponding prefix.
What I needed:
We have value in the response.d that is comma deliminated value. Now I want to export the data of response.d to .csv file.
I have written this function to perform this. I have received the data in response.d but not exporting to the .csv file, so give the solution for this problem to export data in .csv file.
function BindSubDivCSV(){
$.ajax({
type: "POST",
url: "../../WebCodeService.asmx / ShowTrackSectorDepartureList",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);//export to csv function needed here
},
error: function (data) {}
});
return false;
}
In case you have no control over how the server-side works, here is a client-side solution that I have offered in another SO question, pending for that OP's acceptance: Export to CSV using jQuery and html
There are certain restrictions or limitations you will have to consider, as I have mentioned in my answer over there, which has more details.
This is the same demo I have offered:
http://jsfiddle.net/terryyounghk/KPEGU/
And to give you a rough idea of what the script looks like.
What you need to change is how you iterate your data (in the other question's case it was table cells) to construct a valid CSV string. This should be trivial.
$(document).ready(function () {
function exportTableToCSV($table, filename) {
var $rows = $table.find('tr:has(td)'),
// Temporary delimiter characters unlikely to be typed by keyboard
// This is to avoid accidentally splitting the actual contents
tmpColDelim = String.fromCharCode(11), // vertical tab character
tmpRowDelim = String.fromCharCode(0), // null character
// actual delimiter characters for CSV format
colDelim = '","',
rowDelim = '"\r\n"',
// Grab text from table into CSV formatted string
csv = '"' + $rows.map(function (i, row) {
var $row = $(row),
$cols = $row.find('td');
return $cols.map(function (j, col) {
var $col = $(col),
text = $col.text();
return text.replace('"', '""'); // escape double quotes
}).get().join(tmpColDelim);
}).get().join(tmpRowDelim)
.split(tmpRowDelim).join(rowDelim)
.split(tmpColDelim).join(colDelim) + '"',
// Data URI
csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
$(this)
.attr({
'download': filename,
'href': csvData,
'target': '_blank'
});
}
// This must be a hyperlink
$(".export").on('click', function (event) {
// CSV
exportTableToCSV.apply(this, [$('#dvData>table'), 'export.csv']);
// IF CSV, don't do event.preventDefault() or return false
// We actually need this to be a typical hyperlink
});
});
Using the code above (from Terry Young) I found that in Opera it would refuse to give the file a name (simply calling it "download") and would not always work reliably.
To get it to work I had to create a binary blob:
var filename = 'file.csv';
var outputCSV = 'entry1,entry2,entry3';
var blobby = new Blob([outputCSV], {type: 'text/plain'});
$(exportLink).attr({
'download' : filename,
'href': window.URL.createObjectURL(blobby),
'target': '_blank'
});
exportLink.click();
Also note that creating the "exportLink" variable on the fly would not work with Firefox so I had to have this in my HTML file:
<div>
<a id="exportLink"></a>
</div>
Using the above I have successfully tested this using Windows 7 64bit and Opera (v22), Firefox (v29.0.1), and Chrome (v35.0.1916.153 m).
To enable similar functionality (albeit in a far less elegant manner) on Internet Explorer I had to use Downloadify.
My Javascript var contains a 2D array.
If I pop an alert on the the var i get the JSON serialized result, something like:
ID0, DESCRIPTION
I'd like to get each items separated by the , in the value option of the dropdownlist and the other item in the description.
Here's my Javascript code, it would work if split was working correctly but this pops an error because the var doesn't contain a pure string type.
$.ajax(
{
type: "POST",
url: "Projet.aspx/GetDir",
data: "{VP:'" + dd_effort_vp + "',DP:'" + dd_effort_dp + "',Direction:'" + dd_effort_d + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var cars = response.d;
$.each(cars, function(index, value) {
$('#<%= dd_effort_directionp.clientid()%>').append(
$('<option</option>').val(value[value.split(",",0)]).html(value.split(",",1))
}
}
});
I know split doesn't work that way here because of the return value is not a string but you get the result i'd like to achieve, get the first value before the comma has the VALUE of the Dropdownlist and the item after the comma as the HTML text.
Thanks ALOT!
How about value.split(",")[0] instead of value.split(",",0)?
Have you tried value.toString().split(",")?