JS Fiddle Example
OK--I have a field that is a full name (last name, first name). The data that is returning isn't last and first name, it is full name. It is then printed last, first. I want to select just the last name (everything before comma), and set it to uppercase.
I may be mixing jQuery and javascript in my example, I'm not positive--still a newb. However, what I've done in the example is to:
function splitLastName(){
var splitNameArray = $('[data-dojo-attach-point|="physcianNameNode"]').split(",");
var lastName = splitNameArray[0];
var firstName = splitNameArray[1];
lastName.wrap('<span class="isUppercase" />');
}
Basically, I'm setting a variable of the field--I've tested that it accurately grabs the element I want it to grab. I'm turning the string into an array, split by the comma field. Then setting the two parts of the array as their own variables. Finally, attempting to wrap the lastName string in a span that adds the 'isUppercase' class. I know I'm doing something wrong, what is it?
function splitLastName(){
$('[data-dojo-attach-point|="physcianNameNode"]').html(function(i, v) {
var names = v.split(',');
return '<span class="isUppercase">' +names[0] + '</span>,' + names[1];
});
}
Fiddle
.html() docs
The above is a quick solution setting a new innerHTML to the element. If you want to use proper DOM manipulation, it'd be like:
function splitLastName() {
$('[data-dojo-attach-point|="physcianNameNode"]').each(function() {
var names = $(this).text().split(',');
$(this).empty().append($('<span>', {
'class': 'isUppercase',
text: names[0]
}), ',' + names[1]);
});
}
Fiddle
Note that I'm using .each() so the code above will work regardless of $('[data-dojo-attach-point|="physcianNameNode"]') matching multiple elements or just a single one.
The problem is you are trying to split a JQuery object.
I have updated your example: See here
function splitLastName(){
var element = $('[data-dojo-attach-point|="physcianNameNode"]');//find the element
var html = element.html();//get the contents of the DIV element
var splitNameArray = html.split(",");//Split the value with comma
var lastName = splitNameArray[0];//store the last name
var firstName = splitNameArray[1];//store the first name
var newHtml = '<span class="isUppercase">' + lastName + '</span>, ' + firstName;//create the new html using the parsed values
element.html(newHtml);//assign the new html to the original DIV element (overwriting the old)
}
The problem occurs with this line:
var splitNameArray = $('[data-dojo-attach-point|="physcianNameNode"]').split(",");
The notation:
$('< some name >')
is a jQuery selector that selects an element. If you type this into your console (replacing < some name > with your selector) in your browser you'll see that it returns an object not a string. So your code is trying to split an object. I don't know where the string is located (div, span, input box etc.) but you need to pull the string to do the split. If your string is text in a div or span use:
var splitNameArray = ($('[data-dojo-attach-point|="physcianNameNode"]').text()).split(",");
as this will grab the string contained in that selector and then perform the split on it. Likewise, if it is in an input you will need to use the proper handler to get the value:
var splitNameArray = ($('[data-dojo-attach-point|="physcianNameNode"]').val()).split(",");
This will pull the value from an input and then perform the split. If your string is in html then you could alternatively grab it using the following notation:
var splitNameArray = ($('[data-dojo-attach-point|="physcianNameNode"]').html()).split(",");
This will pull the html and perform the respective split operation.
Hope this helps.
Related
I have access to an html string in which I want to search for a specific set of values. So lets say I want to match something from an array...
var array1 = [value1, value2, value3]
If I find value1 in the html string, i want to add a highlight class to that value so it gets highlighted.
var str = htmlString
var res = str.replace('<thead>','<thead class="highlight">');
htmlString = res
Using this i can highlight all the theads, but how could I write it so that I only highlight the theads that contain one of those array values inside of it?
Here's a solution for browser that parses the HTML string into a DOM element, query the DOM tree and manipulate the classList of each selected element, then returns the HTML as a string.
function addClassToElementsByTagName(html, tagName, className) {
var tempElement = document.createElement('div');
tempElement.innerHTML = html;
var elements = tempElement.querySelectorAll(tagName);
elements.forEach(function(element) {
element.classList.add(className);
});
return tempElement.innerHTML;
}
var htmlString = '<table>\n\t<thead>\n\t<tr>\n\t\t<th>Column 1</th>\n\t\t<th>Column 2</th>\n\t\t<th>Column 3</th>\n\t</tr>\n\t</thead>\n</table>';
var result = addClassToElementsByTagName(htmlString, 'thead', 'highlight');
console.log(result);
Gotchas
Keep in mind that element.querySelectorAll() and element.classList.add() are not universally supported. Check out caniuse.com for information regarding each feature.
Also, this is completely dependent on how the browser parses your HTML. If the HTML fails to parse or parses incorrectly, you will experience problems. The .innerHTML property also makes no guarantee that the whitespace provided in the original string will be preserved in the result.
Info's: I have some javascript code that i will show below, who i'm having problem with quotes.
html = [];
style = 'class=odd';
html.push('<li '+style+' onclick=SelectItem("'+ele.id+'","'+idItem+'","'+dsItem+'","'+qtItem+'"); >'+id+' - '+$iObjItensListaVenda.result.ds_item[i]+'</li>');
I have strings that i get from a JSON Object, as you see above.
Problem: But when i'm trying to place it as a Function Parameter on the onClick event of the <li> element, my resulting html <li> element becomes totally unformatted like that:
<li natural,"150");="" white="" american="" onclick="SelectItem("descItem1","2",TELHA" class="odd">00002 - TELHA AMERICAN WHITE NATURAL</li>
What do i want: i need a solution like a function, maybe already exists in jQuery, to Quote my String. Like a QuoteStr("s t r i n g"); to become ""s t r i n g"".
Maybe you're complaining about:
The variable ele is a html <input> element.
The variable idItem contains only numbers, they come from a JSON Object.
The variable dsItem its a string containing Item Description, it comes from the JSON Object too.
The variable qtItem contains only numbers, it is the quantity of the items, it comes from the JSON too.
The sane solution would be to use jQuery to build the element and bind the event handler, not building an HTML string:
var $li = $('<li />', {
"class": "odd",
on: {
click: function() {
SelectItem(ele.id, idItem, dsItem, qtItem);
}
},
text: id + ' - ' + $iObjItensListaVenda.result.ds_item[i]
});
If you are doing this in a loop and the variables end up having the wrong values, please see JavaScript closure inside loops – simple practical example. Alternative you could use jQuery's .data API to set and get those values.
Try \" instead of ' in onClick
$(".container").append("Edit");
You can use quotes in a string by escaping them with a backslash.
var text = "s t r i n g";
"\"" + text + "\"" === "\"s t r i n g\"";
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
You can always use backslash to escape quotes:
console.log('te\'st'); // te'st
console.log("te\"st"); // te"st
You can do the same thing for your string, but I'd suggest you rewrite the whole thing into something more usable. By that I mean not using strings to build objects, but building objects directly.
For example:
var li = document.createElement('li');
li.className = myClass;
li.onclick = function(){/*...*/};
It gets even easier with jQuery.
A third-party control creates an element with an id that looks like:
aspxgv_1803_0_cell1_9_Attribute1^ubd
I need to get the value of this element but jquery seems to have issues with the illegal "^" in the id.
var fieldId = 'aspxgv_1803_0_cell1_9_Attribute1^ubd';
var fieldValue = $('#' + fieldId).val(); // <-------- function stops
How can I get the value of this element?
You can escape the character.
var fieldValue = $('#aspxgv_1803_0_cell1_9_Attribute1\\^ubd').val();
http://jsfiddle.net/82AFA/
If you want a jQuery object of a DOM element you can always just pass the element to the $ function rather than a selector.
var fieldId = 'aspxgv_1803_0_cell1_9_Attribute1^ubd';
var fieldValue = $(document.getElementById(fieldId)).val();
Here's an example using this code to return the html of the jQuery object. http://jsfiddle.net/AZgwm/
I have a String which contains HTML tags:
var str = "Hello World <br><p>1</p><em>My First Javascript</em>";
And i also have a form with hidden input:
<input type='hidden' name='id' value=''>
With that String above, i want to get the value inside <p> tag which is 1 and assign that value to hidden input. And after that, i wanted to remove all the HTML tag inside the string which are these <br><p>1</p><em>My First Javascript</em>. So therefore the only value of str will be Hello World.
Is there any way how to do this on Javascript or jquery?
Thanks guys!
So, what you want to be doing is to convert your string into a jQuery object. You can do so like this -
var str = "Hello World <br><p>1</p><em>My First Javascript</em>";
var $holder = $('<div>');
$holder.append(str);
Now we have your string encapsulated within another div element. Next we extract the value within the <p> element -
var value = $holder.find('p').text(); // 1
Now that we have that value we can place it into the hidden input field -
$('input[name="id"]').val(value);
Now to remove all other elements from the original string - we'll use the container we created earlier for this -
$.each($holder.children(),function(index,elem){
$(elem).remove();
});
Now we can take the textual contents of $holder with $holder.text() and it should be just -
Hello World
If you would like to fiddle with this,
you can do so here - http://jsfiddle.net/TVXbw/1/
Ok, a quick and simple way:
var tmpDiv = document.createElement('div');
tmpDiv.innerHTML = str;//where str is the html string, obviously...
var pTagValue = tmpDiv.getElementsByTagName('p')[0].innerHTML;//=== '1'
document.getElementById('yourInputId').value = pTagValue;
If I understood correctly, that's what you're after, right?
I've got a string of html that I get via $("#datadiv").html();. Within this data are several other elements, and what I would like to do is append some data to one of those elements.
e.g.
var data = $("#datadiv").html();
var somestring = "Some text"
then append somestring into the div #stringholder inside of data. Is this possible?
And before the question comes, no I can't add it to the div before doing $("#datadiv").html();.
You can do something like this:
$(data).find("#stringholder").append(somestring);
As the html method returns a string, you need to pass it into jQuery again to create a jQuery object. You can then call find to get the element you want, and append to append the other string.
jQuery is quite happy to accept a string of HTML as an argument. It's not just selector strings that are accepted. If you pass in a string of HTML, that fragment will be the context for further method calls.
I think you already know this, but note that this will not affect the HTML in the DOM. It will only affect the fragment produced by passing the string into jQuery.
Do you mean :
var data = $("#datadiv").html();
var somestring = "Some text"
var newData = data + " " + somestring;
var holderData = $("#stringholder").html();
var newestData = holderData + " " + newData;
$("#stringholder").html('');
$("#stringholder").html(newestData);
Sure. Basically you could dump the string from the current div in to a variable and then concate the additional text and put it back in the div.
var someText = $('#datadiv').html()
var someNewText = 'my new text'
var someText = someText + ' ' + someNewText
$('#datadiv').html('') //this will clear the current text but not really necessary.
$('#datadiv').html('someText')
you just need to have some event that fires to trigger everything.