I have a variable that contains HTML.
var html = '<p><span id="variable:7" class="variable-source" title="variable:TEXT_CONTAINER">DATA</span> This is a variable</p>'+
'<p><span id="input:10.New Input 2" class="input-source" title="New Screen; New Input 2">DATA</span> This is a input source</p>'+
'<p>Testing</p>';
I am trying to loop around all of the elements and replace with spans specific date. So any spans with a class of variable-source will need to be replaced with specific date, and the same for input-source.
I have tried to use the following:
$('span', html).replaceWith(function () {
var id = $(this).attr('id');
// this returns the correct id
//calculations go here
var value = 'testing';
return value
});
Which outputs the following:
testing This is a variable
All of the paragraph tags have been removed, and it seems to stop after the first paragraph. Is there something that I am missing here? I can post more code or explain more if needed.
Thanks in advance.
You need to create a html object reference, else you won't get a reference to the updated content. Then get the update content from the created jQuery object after doing the replace operations
var html = '<p><span id="variable:7" class="variable-source" title="variable:TEXT_CONTAINER">DATA</span> This is a variable</p>' +
'<p><span id="input:10.New Input 2" class="input-source" title="New Screen; New Input 2">DATA</span> This is a input source</p>' +
'<p>Testing</p>';
var $html = $('<div></div>', {
html: html
});
$html.find('span.variable-source').replaceWith(function() {
var id = this.id;
// this returns the correct id
//calculations go here
var value = 'replaced variable for: ' + id;
return value
});
$html.find('span.input-source').replaceWith(function() {
var id = this.id;
// this returns the correct id
//calculations go here
var value = 'replaced input for: ' + id;
return value
});
var result = $html.html();
$('#result').text(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
Related
Maybe I am confusing this a bit, but I have a piece of code that works like the following:
$("#myButton").on('click', function(){
var myValue = $('#myInput').val();
listSize++;
var listItem = "<li>" + myValue + "<input type='hidden' name='foo" +
listSize + "' value='" + myValue + "' /></li>";
$("ol.myList").append(listItem);
});
If the text input value contains for example, a ', then this code breaks in terms of correctly adding the hidden input value.
I was thinking that using encodeURIComponent would do the trick, but it does not.
What's the proper way to handle this?
Instead of doing this with html strings, create an actual element and set it's value property using val().
You can sanitize any possible html out of it by first inserting the string into a content element as text and retrieving it as text.
Note that the value property does not get rendered in the html the same as value attribute does so quotes are not an issue
$("#myButton").on('click', function(){
// sanitize any html in the existing input
var myValue = $('<div>', {text:$('#myInput').val())).text();
listSize++;
// create new elements
var $listItem = $("<li>",{text: myValue});
// set value of input after creating the element
var $input = $('<input>',{ type:'hidden', name:'foo'+listSize}).val(myValue);
//append input to list item
$listItem.append($input);
// append in dom
$("ol.myList").append($listItem);
});
I think this is what you are looking for:
$("#myButton").on('click', function(){
var myValue = $('#myInput').val();
listSize++;
var listItemHTML = "<li>" + myValue + "<input type='hidden' name='foo'></li>";
$(listItemHTML).appendTo('ol.myList').find('input[type=hidden]').val(myValue);
});
The appendTo function returns a reference to the just appended element.
Calling the val() function on the element will render the inserting of a quote useless since it will be interpreted as an actual value.
Safest way would be to write a wrapper
function addslashes (str) {
return (str + '')
.replace(/[\\"']/g, '\\$&')
.replace(/\u0000/g, '\\0')
}
var test= "Mr. Jone's car";
console.log(addslashes(test));
//"Mr. Jone\'s car"
I have some javascript/JQuery which allows me to create a new entry in an HTML ordered list. This works fine. But now I am trying to set each entry to have an id equal to a variable 'id''s value, so that I can identify an entry and remove its id from a javascript array.
I am being told that I can't use setAttribute OR defineProperty, so I don't know what to do! I am including both my attempts to demonstrate what I am trying to achieve:
var idList = []; //array of entry ids
$(function (){
$("#click-me").click(function (e){
e.preventDefault();
i++;
var list = $("#list"); //works fine
var name = $("#colleague-select option:selected").text(); //works fine
var id = $("#colleague-select").val(); //works fine
var remove = "<button type='button' class='remove-me'> X </button>"; //works fine
var entry = "<li>" + name + remove+ "</li>"; //works fine
//entry.setAttribute("id", id); //doesn't work
//or
Object.defineProperty(entry, 'id', {
get: function(){return id;},
set: function(value) {id = value;}
});
list.append(entry); //adds entry to HTML element 'list'
idList.push(id); //adds id to array which should be the same as entry's id
return false;
});
});
$(document).on('click', ".remove-me", function(){
var entry = $(this).parent();
entry.remove();
var id = entry.attr("id"); //gets value of attribute "id". How will this need to be changed?
var index = idList.indexOf(id); //finds the index number of id within array
idList.splice(index,1); //removes id from array
});
Help on how to do this will be much appreciated, thanks
Entry is a string of html not an dom node, you can create an jQuery object out of it and then add the attribute or just add the id in the string
var entry = $("<li>" + name + remove+ "</li>").attr('id', id); //works fine
or
var entry = "<li id=\""+id+"\">" + name + remove+ "</li>"; //works fine
The click event on .remove-me doesn't work because you're calling entry.remove() and afterwards entry.attr("id"). At that point the entry element has been removed and thus you can't the get the id.
Move entry.remove() below entry.attr("id").
I am trying to get all span elements inside the form. The span elements are turning into input text fields and become editable. When you click away they are turning back into span elements. I will attached fiddle live example.
I gave it a go but the problem is that I am getting both ids but only value of the first span element.
Here is my html:
<span name="inputEditableTest" class="pztest" id="inputEditableTest" data-editable="">First Element</span>
<span name="inputEditableTest2" class="pztest" id="inputEditableTest2" data-editable="">Second Element</span>
<input id="test" type="submit" class="btn btn-primary" value="Submit">
And here is JavaScript with jQuery:
$('body').on('click', '[data-editable]', function () {
var $el = $(this);
var name = $($el).attr('name');
var value = $($el).text();
console.log(name);
var $input = $('<input name="' + name + '" id="' + name + '" value="' + value + '"/>').val($el.text());
$el.replaceWith($input);
var save = function () {
var $p = $('<span data-editable class="pztest" name="' + name + '" id="' + name + '" />').text($input.val());
$input.replaceWith($p);
};
$input.one('blur', save).focus();
});
$("#test").on('click', function(){
var ok = $("span")
.map(function () {
return this.id;
})
.get()
.join();
var ok2 = $("#" + ok).text();
alert(ok);
alert(ok2);
//return [ok, ok2];
});
Here is the fiddle https://jsfiddle.net/v427zbo1/3/
I would like to return the results as an array example:
{element id : element value}
How can I read ids and values only inside specific form so something like:
<form id = "editableForm">
<span id="test1">Need these details</span>
<span id="test2">Need these details</span>
<input type="submit">
</form>
<span id="test3">Don't need details of this span</span>
Lets say I have got more than 1 form on the page and I want JavaScript to detect which form has been submitted and grab values of these span elements inside the form
I will be grateful for any help
$("#test").on('click', function(){
var result = {};
$("span").each(function (k, v) {
result[v.id] = v.innerHTML;
});
alert(JSON.stringify(result));
//return [ok, ok2];
});
Here is an example: https://jsfiddle.net/v427zbo1/4/
Container issue:
You should use this selector: #editableForm span if you want to get all the divs inside this container.
$("#editableForm span").each(function (k, v) {
result[v.id] = v.innerHTML;
});
But if you want to get only first-level children elements then you should use this selector: #editableForm > span
Example with getting all the spans inside #editableForm container: https://jsfiddle.net/v427zbo1/9/
If you want to have several forms, then you can do like this:
$('form').on('submit', function(e){
e.preventDefault();
var result = {};
$(this).find('span').each(function (k, v) {
result[v.id] = v.innerHTML;
});
alert(JSON.stringify(result));
//return [ok, ok2];
});
Example with two forms: https://jsfiddle.net/v427zbo1/10/
You can't use .text to return the value of multiple elements. It doesn't matter how many elements are selected, .text will only return the value of the first one.
Virtually all jQuery methods that return a value behave this way.
If you want to get an array of values for an array of matched elements, you need another map. You also need to join the strings with , # as you're producing something along the lines of #id1id2id3 instead of #id1, #id2, #id3:
var ok = $("span").map(function () {
return this.id;
}).join(', #')
var ok2 = $("#" + ok).map(function () {
return $(this).text();
});
That said, you're already selecting the right set of elements in your first map. You pass over each element to get its ID, you already have the element. There is no reason to throw it away and reselect the same thing by its ID.
If I got you right following code will do the job
var ok = $("span")
.map(function () {
return {id: $(this).attr('id') , value: $(this).text()};
}).get();
Check this fiddle.
I have a following html string of contentString:
var content =
'<div id="content">' +
'<div>' +
'<input name="tBox" id="select" type="checkbox" value="" '+
'onclick="changeView()"> Select for operation' +
'<p style="text-align:right">View details</p>' +
'</div>' +
'</div>';
Here, How I find the checkbox select by id and add attribute checked on changeView() function?
function changeView(m) {
//find the select id from content string
var checkbox = content.find($('#select'+m));
// Apply the checked property on checkbox.
checkbox.attr("checked","checked");
}
Thanks in advance.
If you convert it to a JQuery object first then you can do it like this:
var contentObj = $(content);
var checkbox = contentObj.find("#select");
checkbox.attr("checked", true);
then if you need it back at html string:
content = contentObj[0].outerHTML;
Note: If outerHTML is not working as expected, the following JQuery can be used as an alternative:
content = contentObj.clone().wrap('<div>').parent().html();
If m is meant to be the id you want to find (e.g. "select"), then use this:
var checkbox = contentObj.find("#" + m);
Live Example: Here is a working example
Here is the complete function for easy reference:
function changeView(m) {
var contentObj = $(content);
var checkbox = contentObj.find("#" + m);
checkbox.attr("checked", true);
content = contentObj[0].outerHTML;
}
You need to compile the string into a DOM object first by wrapping it in a jQuery call first. Then you can use the find method.
So:
var dom = $(content),
select = dom.find('#select');
In any case, there is no need to add the 'checked' attribute, because when you click the checkbox, it will automatically become checked.
If however, you want to still programmatically check it:
select.on('click', function () {
this.attr('checked', 'checked');
});
Simply like this
function changeView(m) {
//find the select id from content string
var checkbox = content.find('#select');
// Apply the checked property on checkbox.
checkbox.attr("checked","checked");
}
if you want to pass id then
function changeView(m) {
//find the select id from content string
var checkbox = content.find("#" + m);
// Apply the checked property on checkbox.
checkbox.attr("checked","checked");
}
Since you're using the onclick handler, you don't really need to do any of that :
in html : onclick="changeView(this);"
function changeView(box) {
if(box.checked) { stuff; }
// or get jquery ref to that box :
$(box).prop("checked", true);
}
I have 4 <div> tag and <a> tag for each <div> tags.
In each and every div tag i have inserted 2 span tag and a a tag.
When the a tag is clicked i need to get the product name and the price of that div
Here is the demo http://jsfiddle.net/8VCWU/
I get the below warning message when i use the codes in the answer ...
Try this:
$(".get").click(function(e) {
e.preventDefault();
var $parent = $(this).closest(".item");
var itemName = $(".postname", $parent).text();
var itemPrice = $(".price", $parent).text();
alert(itemName + " / " + itemPrice);
});
Example fiddle
Note that you had a lot of repeated id attributes which is invalid code and will cause you problems. I've converted the #item elements and their children to use classes instead.
jQuery
$(".get").click(function(event){
event.preventDefault(); /*To Prevent the anchors to take the browser to a new URL */
var item = $(this).parent().find('#postname').text();
var price = $(this).parent().find('#price').text();
var result = item + " " + price;
alert(result)
});
DEMO
A Quick Note about id:
The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document).
A unique identifier so that you can identify the element with. You can use this as a parameter to getElementById() and other DOM functions and to reference the element in style sheets.
solution is below
use the blow code and try it
<a data-role="link" href="javascript:linkHandler('<%= obj.productname %>', '<%= obj.price %>')" class="get" >Add <a>
function linkHandler(name, price)
{
alert(name);
alert(price);
var name = name;
var price = price;
var cartItem = new item(name, parseFloat(price));
// check duplicate
var match = ko.utils.arrayFirst(viewModel.cartItems(), function(item){ return item.name == name; });
if(match){
match.qty(match.qty() + 1);
} else {
viewModel.cartItems.push(cartItem);
var rowCount = document.getElementById("cartcontent1").getElementsByTagName("TR").length;
document.getElementById("Totala").innerHTML = rowCount;
}
}
with jQuery
$('a.get').on('click',function(){
var parent = $(this).parent();
var name = $(parent+' #postname').text();
var price = $(parent+' #price').text();
});
Or again:
$('a').click(function(e){
e.preventDefault();
var $price = $(this).siblings('#price').text();
var $postname = $(this).siblings('#postname').text();
alert($price);
alert($postname);
});
Try
function getPrice(currentClickObject)
{
var priceSpan = $(currentClickObject).parent("div:first").children("#price");
alert($(priceSpan).html());
}
and add to your a tag:
...
I'd suggest to use classed instead of id if you have more than one in your code.
The function you're looking for is siblings() http://api.jquery.com/siblings/
Here's your updated fiddle:
http://jsfiddle.net/8VCWU/14/
Hi I cleaned up the HTML as mentioned using the same Id more than once is a problem.
Using jQuery and the markup I provided the solution is trivial.
Make a note of the CSS on the below fiddle
http://jsfiddle.net/8VCWU/27/
$(document).ready(function(){
$("#itmLst a.get").click(function(){
var $lstItm = $(this).parents("li:first");
var pName = $lstItm.find("span.postname").html();
var price = $lstItm.find("span.price").html();
alert("Product Name: " + pName + " ; Price: " + price);
});
});
I have made some changes in your html tags and replace all repeated Ids with class, because you have repeated many ids in your html and it causes trouble so it is wrong structure. In HTML, you have to give unique id to each and every tag. it will not be conflicted with any other tag.
Here i have done complete bins demo. i have also specified all alternative ways to find tag content using proper jQuery selector. the demo link is as below:
Demo: http://codebins.com/bin/4ldqp8v
jQuery
$(function() {
$("a.get").click(function() {
var itemName = $(this).parent().find(".postname").text().trim();
var itemPrice = $(this).parent().find(".price").text().trim();
//OR another Alternate
// var itemName=$(this).parents(".item").find(".postname").text().trim();
// var itemPrice=$(this).parents(".item").find(".price").text().trim();
//OR another Alternate
//var itemName=$(this).closest(".item").find(".postname").text().trim();
// var itemPrice=$(this).closest(".item").find(".price").text().trim();
//OR another Alternate
//var itemName=$(this).siblings(".postname").text().trim();
//var itemPrice=$(this).siblings(".price").text().trim();
alert(itemName + " / " + itemPrice);
});
});
Demo: http://codebins.com/bin/4ldqp8v
You can check above all alternatives by un-commenting one by one. all are working fine.