How to append '#' to the value in Javascript - javascript

Can anyone please help me how to append '#' to the value as below:
My code is below:
var idselvalue = '#'+idvalue;
console.log("IDSELVALUE"+idselvalue); // Printing as ::: #"T2"
( I want this to be printed as "#T2" so that I want to include the below)
$('#idselvalue').val(usrObj); // to display the selected option in the select box
if I hard the value as below:
$('#T2').val("26");
I also need help how to retrieve all the selected options, as of now I'm able to get only one first selected option
Below is my code:::
$(document).ready(function () {
var usrObj = getCookie("selectedEXP");
var idvalue = getCookie("selectedIDValue");
var idselvalue = '#'+idvalue;
console.log("IDSELVALUE"+idselvalue);
$('#idselvalue').val(usrObj);
console.log("OnLoad Calling usrObj"+usrObj);
console.log("OnLoad Calling idvalue"+idvalue);
//Printing only one selected options
});
Appreciate your help! Thanks in advance :)

Try using the following:
var idselvalue = function(d){return "#"+idvalue;}
along with scrappedcola's suggestion:
$('#idselvalue').val(usrObj); should be $(idselvalue) you already appended a # to the beginning and js can't determine the var from the string, it will just treat the entire thing as a string.

I've solved it by removing the double quotes for the idvalue and userobj as below:
var idselvalue = '#'+idvalue.replace(/\"/g, "");
var selusrObj = usrObj.replace(/\"/g, "");
$(idselvalue).val(selusrObj);
It is working fine...
Thank you!

Related

Passing a variable inside a Set attribute value

Can someone please let me know if it is possible to pass a variable inside a "setAttribute" to make an input value appear in an href link?
For example I have :
var inputNumber = document.getElementById('inputNumber').value;
var validateBtn = document.getElementsByTagName("a"); //a surrounding n button
var linkValidation = validateBtn[0].href = ("https://checkyournumber.com.action?inputNumber=" + inputNumber );
so far so good, if i console.log linkValidation, i do have the full link with the input number at the end as intended.
However when i try to set the href attribute to the a tag in the html using the below :
document.getElementsByTagName("a")[0].setAttribute("href", "https://checkyournumber.com.action?inputNumber=" + inputNumber );
Then the link the user is taken to is : https://checkyournumber.com.action?inputNumber=
I have tried entering inputNumber inside the "" but then of course it is displayed as such in the URL. I have tried with '' instead... no luck.
Would someone know if it is possible at all?
Thank you very much for your support in advance!
Try as follows
(function() {
var inputNumber = document.getElementById('inputNumber').value;
var validateBtn = document.getElementsByTagName("a"); //a surrounding n button
var linkValidation = validateBtn[0].href = ("https://checkyournumber.com.action?inputNumber=" + inputNumber );
});

Parse a string in jquery, change something and get the modified string back

I have a string containing html code, something like this: http://jsbin.com/ocoteg/1.
I want to parse this string, make some changes (just for example: change all links to a span), and then get the modified html string back.
Here is a jsbin, where I started this, but I can't make it work: http://jsbin.com/okireb/1/edit.
I get the html string, I parse it with jquery, but I can't replace the links, and get the modified html string back.
UPDATE
Why the downvote? What is the problem with this question?
You can do it in a loop also
dom.each(function(i,v){
if(v.tagName == "A"){
dom[i] = $('<span/>').html($(v).html())[0]; // replace it right away with new span element
}
});
var newString = $('<div>').append(dom.clone()).html(); //<-- to get new string http://stackoverflow.com/a/652771/1385672
console.log(newString);​
EDIT:
Here's how you can do it keeping the other tags
var dom = $(text.split('\n'));
$(dom).each(function(i,v){
var ele = $(v)[0];
if($(ele).is('a')){
dom[i] = $('<div>').append($('<span/>').html($(v).html())).html();
}
});
var newString = dom.get().join('\n');
http://jsbin.com/okireb/32/edit
Use find instead of filter :
var dom = $('<div>'+text+'</div>');
dom.find('a').each(function() {
var el = $(this);
var html = el.html();
var span = $('<span/>').html(html);
el.replaceWith(span);
});
console.log(dom.children()); ​
Note that I wrap everything for the case where the initial dom isn't one element.
Demonstration
To get the html back as a string use
var html = dom.html();
This should be what you want (can be improved)
var text = '<!DOCTYPE html><html><head><meta charset=utf-8 /><title>JS Bin</title></head><body>Link 1Link 2Link 3</body></html>';
var body_content = text.substring(text.indexOf('<body>') + 6, text.indexOf('</body>'));
var $dom = $('<div/>').html(body_content);
$('a', $dom).each(function() {
$('<span>' + $(this).html() + '</span>').insertAfter($(this));
$(this).remove();
});
var text_new = text.replace(body_content, $dom.html());
// text_new contains the entire HTML document with the links changed into spans
You could do it with .replace.
Probably not the nicest way of doing it though.
dom = dom.replace(/<a /g,'<span');
dom = dom.replace(/<\/a>/g,'</span>');
Demo: http://jsbin.com/okireb/14/edit

Add a js function to the DOM?

I have a very simple HTML page. After everything is loaded, the user can interact with it perfectly. Now, at some point, the user clicks on an element. An ajax call is made and new data is being requested. I now want to remove the previous element the user clicked on with the element(s) the user has requested (on the same page) - practically remove the old element from the DOM and add the new one. Well, I did this as well, but I am unable to add a function to the newly created element. This is my function:
setCountry = function(value){
document.getElementById('country').innerHTML = value;
}
and I'm trying to add it like this to my element
a_tag.setAttribute("href", "javascript:setCountry(countries[i]);");
The function is being called and writes "undefined" to the innerHTML element. I set the attribute using a for loop and just above the for loop I alert an element from the array to be sure it's correct, and it prints out the correct value.
I assume the problem happens because the function is being created on the first load of the DOM, but I'm not sure. Can anyone shed some light on what is really happening here and what I should do to correct it? I want to be able to add more functions so not looking for a work around writing an innerHTML tag, I just want to understand what I'm doing wrong.
Thank you.
Edited with more code
//declare an array to hold all countries form the db
var countries = new Array();
function getCountries(region) {
document.getElementById('scroller').innerHTML = '';
//send the data to the server and retreive a list of all the countries based on the current region
$.ajax({
type: "POST",
url: "scripts/get_countries.php",
data: {
region: region
},
success: saveDataToArray,
async: false,
dataType: 'json'
});
//save the data to an array
function saveDataToArray(data){
var i = 0;
while (data[i]){
countries[i] = data[i];
i++;
}
}
scroller = document.getElementById('scroller');
//create a ul element
var holder = document.createElement("ul");
//here create a back button which will recreate the whole list of regions
var total = countries.length;
for(i=0;i<total;i++){
//create the first field in the list
var bullet_item = document.createElement("li");
//create an a tag for the element
var a_tag = document.createElement("a");
//set the redirect of the tag
a_tag.setAttribute("href", "javascript:setCountry(this);");
//create some text for the a_tag
var bullet_text = document.createTextNode(countries[i]);
//apend the text to the correct element
a_tag.appendChild(bullet_text);
//apend the a_tag to the li element
bullet_item.appendChild(a_tag);
//apend the item to the list
holder.appendChild(bullet_item);
}
//apend the holder to the scroller
scroller.appendChild(holder);
}
function setRegion(region){
document.getElementById('region').innerHTML = region;
}
setCountry = function(value){
document.getElementById('country').innerHTML = value;
}
There is no need for quoting the code in a string. Instead of this:
a_tag.setAttribute("href", "javascript:...")
Try to form a closure:
a_tag.onclick = function () { ... }
Note that by default <A> elements without HREF do not look normal, but you can fix that with CSS.
Problem solved
Everything was good apart from the way I was declaring the href parameter
a_tag.setAttribute("href", "javascript:setCountry("+'"'+countries[i]+'"'+")");
it's all the usual, a game of single quotes and double quotes.
Thanks everyone for pitching in ideas. Much appreciated as usual
Adrian

Jquery script freezing browser but working

i'm trying to make a live search for my mobile website, I don't want to query the database every time a user type a letter so I created a ordered list with all the names that can be searched for and i'm looping through it with jquery, problem is that I have 3300 names and it's freezing the browser when it searches through them, can anyone give me a tip about better ways to do it? here is my code:
$(document).ready(function(){
$("input#search").keyup(function(){
var filter = $(this).val(), count = 0;
var html = "";
$("ol.pacientes li").each(function(){
var nome_paciente = $(this).text();
if(nome_paciente.indexOf(filter.toUpperCase()) != -1){
html = html + " " + nome_paciente;
}
$('#pacientes_hint').html(html);
});
Use the jQuery autocomplete version. You can load an array with all your names and pass it in to autocomplete, which will work on the fly.
http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/
You could change your each to:
var text = $("ol.pacientes li:contains(\""+filter.toUpperCase()+"\")").map(function() {
return $(this).text();
}).join(' ');
$('#pacientes_hint').text(text);
Besides being shorter, the only improvement will be setting the contents of $('#pacientes_hint') only at the end, which could help.
Let me know if you need a more creative solution.
First of all, you could move #pacientes_hint outside the each function.
$(document).ready(function(){
$("input#search").keyup(function(){
var filter = $(this).val(), count = 0;
var html = "";
$("ol.pacientes li").each(function(){
var nome_paciente = $(this).text();
if(nome_paciente.indexOf(filter.toUpperCase()) != -1){
html = html + " " + nome_paciente;
} // end if
}); // end each
$('#pacientes_hint').html(html);
Then, you can define ol.pacientes as a variable before the keyup handler, so it doesn't look for it everytime and in the each function, search inside the variable:
$(document).ready(function(){
var pacientes_list = $("ol.pacientes");
var pacientes_hint = $("#pacientes_hint");
$("input#search").keyup(function(){
...
$("li", $(pacientes_list)).each(function(){ // search in the container
...
}); // end each
$(pacientes_hint).html(html);

Altering the value of an option (select) element?

I'm attempting to select the selected value of a <select> form element, and append the value with -R. (This will be for regex matching later on). Anyway, so far I've tried the following:
Attempt 1:
var country = $('select[name=g_country\\['+value+'\\]]').val();
$('select[name=g_country\\['+value+'\\]]').find('option[value=' + value +']').val(country + '-R');
Attempt 2:
var country = $('select[name=g_country\\['+value+'\\]]').val();
$('select[name=g_country\\['+value+'\\]]').val(country + '-R');
I can tell that the selection of the correct form element (using delete_x, where x is a number) works fine, as the form elements to disable when .select-delete is clicked, however the value setting doesn't. The commented portion down the bottom is what I've been using to check the value of the <select> element post-value change (or what should be post-value change).
Here's a link to my jsFiddle: http://jsfiddle.net/gPF8X/11/
Any help/edits/answers will be greatly appreciated!
Try this:
$('.select-delete').click( function() {
var value = $(this).attr('id');
value = value.replace('delete_', '');
var country = $('select[name=g_country\\['+value+'\\]] option:selected').val() + '-R';
alert(country);
$('select[name=g_country\\['+value+'\\]] option:selected').val(country);
$('select[name=g_country\\['+value+'\\]]').attr('disabled','1');
$('input[name=g_url\\['+value+'\\]]').attr('disabled','1');
$(this).css('display', 'none');
var check = $('select[name=g_country\\['+value+'\\]]').val();
$('#test').append(check);
});
There is an issue with your HTML as well.
Finally came up with the right selector, props to #gjohn for the idea.
Here's my final working code, that appropriately adds -R to the end of g_country[x]:
$('.select-delete').click( function() {
var value = $(this).attr('id');
value = value.replace('delete_', '');
var country = $('select[name=g_country\\['+value+'\\]]').val();
$('select[name=g_country\\['+value+'\\]] > option:selected').val(country + '-R');
$('select[name=g_country\\['+value+'\\]]').attr('disabled','1');
$('input[name=g_url\\['+value+'\\]]').attr('disabled','1');
$(this).css('display', 'none');
});

Categories