I have the following script works for the replace with jQuery in innerHTML.
HTML code
<input type="submit" name="replace" id="replace" value="Replace" />
<div class="my_div">Default1 content1</div>
<div class="my_div">Default2 content2</div>
java script
$('#replace').click(function() {
$('.my_div').html(function( idx, oldHtml){
return oldHtml.replace(/Default1|content1|Default2|content2/gi, 'symbol1');
});
});
But I couldn't modify the script for multiple unique replacement. Example I want to replace
Default1 to symbol1
Default2 to symbol2
content1 to symbol3
content2 to symbol4
the following doesn't work
$('#replace').click(function() {
$('.my_div').html(function( idx, oldHtml){
return oldHtml.replace(/Default1/gi, 'symbol1');
return oldHtml.replace(/Default2/gi, 'symbol2');
return oldHtml.replace(/content1/gi, 'symbol3');
return oldHtml.replace(/content2/gi, 'symbol4');
});
});
Also I had early script based on id attribute, which is more than 500 replace lines. Is it possible that I can include similar structure in this new jQuery class attribute?
var str=document.getElementById("my_id").innerHTML;
var n=str.replace("Default1","symbol1");
var n=str.replace("Default2","symbol2");
document.getElementById("my_id").innerHTML=n;
}
Thanks a lot, you guys helped me a lot. :)
Question 1 :
Replace
return oldHtml.replace(/Default1/gi, 'symbol1');
return oldHtml.replace(/Default2/gi, 'symbol2');
return oldHtml.replace(/content1/gi, 'symbol3');
return oldHtml.replace(/content2/gi, 'symbol4');
with
return oldHtml.replace(/Default1/gi, 'symbol1')
.replace(/Default2/gi, 'symbol2')
.replace(/content1/gi, 'symbol3')
.replace(/content2/gi, 'symbol4');
Question 2 :
Replace
var str=document.getElementById("my_id").innerHTML;
var n=str.replace("Default1","symbol1");
var n=str.replace("Default2","symbol2");
document.getElementById("my_id").innerHTML=n;
with
var $div = $('#my_id');
$div.html(
$div.html().replace("Default1","symbol1")
.replace("Default2","symbol2")
);
(if you use jQuery, no need for those getElementById)
Related
I would like to manipulate values on a JQuery template, perhaps with an inline expression or function. I am having trouble selecting the elements in order which to grab their values to perform these tasks. Here's the code:
<td class="currency">
<span id="discounted_amount">${Globalize.format(DiscountAmount, "c2")}</span>
</td>
<td class="currency">
<span id="totalAmt">${Globalize.format(InvoiceAmount, "c2")}</span>
</td>
I'm trying to basically evaluate the discounted_amount, and if there's a value, to subtract that from the totalAmt. I would like to do this on the client, without any further ajax calls. I've seen some examples of this where people have used {{if}} {{else}} {{/if}} or {{html somefunction();}}. I've just not had any success myself. Here's the function I'd like to call, or a similar structure based on whatever works best for the jquery template implementation.
function calculateDiscountedTotal() {
var discountedAmount = $('#discounted_amount').val();
var totalAmt = $('#total_amount').val();
var discountedTotal = function () {
return totalAmt - discountedAmount;
}
return discountedTotal();
}
I am unsure what template system you're using but it looks like you want the element text not the value. Value is reserved for input elements.
var discountedAmount = parseInt($('#discountered_amount').text());
function calculateDiscountedTotal() {
var discountedAmount = parseInt( $('#discounted_amount').text());
var totalAmt = parseInt($('#totalAmt').text());
var discountedTotal = function () {
return totalAmt - discountedAmount;
}
return discountedTotal();
}
console.log(calculateDiscountedTotal());
});`enter code here`
In the following HTML markup, how can I get the value of the input field which has the name module_id[], by clicking on the span class .click.
HTML:
<div class="module">
<div class="info">..</div>
<div class="ctrl"><span class="click">Click</span></div>
<input type="hidden" value="module1" name="module_id[]" />
<input type="hidden" value="title" name="module_title[]" />
</div>
I have tried this:
jQuery:
$('.module').on('click','.click',function(){
var target_module = $(this).parent();
var module_id = target_module.find('input[name=module_id\\[\\]]').val();
alert(module_id);
});
Demo:
http://jsfiddle.net/FKdNJ/
$(this).parent(); is giving you the <div class="ctrl"> instead.
You could use $(this).parent().parent(), but a more flexible solution is to use closest() instead;
$(this).closest('.module');
You can see this working here; http://jsfiddle.net/FKdNJ/5/
FWIW, you could also change your approach completely, and use e.delegateTarget to retrieve the .module element directly (http://jsfiddle.net/FKdNJ/7/);
$('.module').on('click','.click',function(e){
var target_module = $(e.delegateTarget);
var module_id = target_module.find('input[name=module_id\\[\\]]').val();
alert(module_id);
});
With:
$('input[name="module_id[]"').val();
jsFiddle example 1
$('.module').on('click', '.click', function () {
console.log($('input[name="module_id[]"').val());
});
If you have more than one set of this block of code, use $(this).closest('.ctrl').next().val():
as in:
$('.module').on('click', '.click', function () {
console.log($(this).closest('.ctrl').next().val());
});
jsFiddle example 2
Try this
$('.module').on('click','.click',function(){
alert($(this).closest('.module').find('[name="module_id[]"]:first').val())
});
http://jsfiddle.net/FKdNJ/3/
Try this. You're probably better off using html 5 data- attributes if possible.
$('span.click').click(function(){
var moduleId = $(this).closest("div.module").find("input[name='module_id[]']").val()
alert(moduleId);
});
I have added a answer in fiddle:
$('.click').on('click',function(){
alert($('input[name=module_id\\[\\]]').val());
})
http://jsfiddle.net/FKdNJ/6/
I need to get the next textarea, but I'm not being able with next or even find.
Sample code HTML:
<div>
<div class="guides_chapters_button" onclick="surroundtest('[center]', '[/center]');">Center</div>
<div class="guides_chapters_button" style="text-decoration: underline;" onclick="surround('[u]', '[/u]');">u</div>
</div>
<textarea class="guides_chapters_textarea" id="textareamatch" name="matchupm" rows="7" cols="25"></textarea>
JS:
window.surround = function surround(text2,text3){
$("#textareamatch").surroundSelectedText(text2, text3);
}
function surroundtest(text2,text3){
var c = $(this).parent().next('textarea');
c.surroundSelectedText(text2, text3);
}
JS FIDDLE: http://jsfiddle.net/qmpY8/1/
What I need working is surroundtest, the other is an example working but using the id. I would love to replace that one because Im usinc cloned objects.
The this statement in surroundtest applies to the window object and not the element. What you should do is to change the function definition as so:
function surroundtest(element, text2,text3){
var c = $(element).parent().next('textarea');
...
}
And the HTML accordingly:
<div class="guides_chapters_button" onclick="surroundtest(this, '[center]', '[/center]');">Center</div>
If this is the HTML you are going with, then .closest() can also be used to get the textarea element.Like below:
var c = $(element).parent().closest('textarea');
I'm trying to convert newline characters (\n) to html br's.
As per this discussion in the Google Group, here's what I've got:
myApp.filter('newlines', function () {
return function(text) {
return text.replace(/\n/g, '<br/>');
}
});
The discussion there also advises to use the following in the view:
{{ dataFromModel | newline | html }}
This seems to be using the old html filter, whereas now we're supposed to use the ng-bind-html attribute.
Regardless, this poses a problem: I don't want any HTML from the original string (dataFromModel) to be rendered as HTML; only the br's.
For example, given the following string:
While 7 > 5
I still don't want html & stuff in here...
I'd want it to output:
While 7 > 5<br>I still don't want html & stuff in here...
Is there any way to accomplish this?
Maybe you can achieve this only with html, a <preformated text> way ? It will avoid from using filters or do any kind of processing.
All you have to do is display the text within an element that has this CSS:
<p style="white-space: pre;">{{ MyMultiLineText}}</p>
This will parse and display \n as new lines. Works great for me.
Here, a jsFiddle example.
Instead of messing with new directives, I decided to just use 2 filters:
App.filter('newlines', function () {
return function(text) {
return text.replace(/\n/g, '<br/>');
}
})
.filter('noHTML', function () {
return function(text) {
return text
.replace(/&/g, '&')
.replace(/>/g, '>')
.replace(/</g, '<');
}
});
Then, in my view, I pipe one into the other:
<span ng-bind-html-unsafe="dataFromModel | noHTML | newlines"></span>
A simpler way to do this is to make a filter that splits the text at each \n into a list, and then to use `ng-repeat.
The filter:
App.filter('newlines', function() {
return function(text) {
return text.split(/\n/g);
};
});
and in the html:
<span ng-repeat="line in (text | newlines) track by $index">
<p> {{line}}</p>
<br>
</span>
If you do not want to destroy the layout with endless strings, use pre-line:
<p style="white-space: pre-line;">{{ MyMultiLineText}}</p>
I'm not aware if Angular has a service to strip html, but it seems you need to remove html before passing your newlines custom filter. The way I would do it is through a custom no-html directive, which would be passed a scope property and the name of a filter to apply after removing the html
<div no-html="data" post-filter="newlines"></div>
Here's the implementation
app.directive('noHtml', function($filter){
return function(scope, element, attrs){
var html = scope[attrs.noHtml];
var text = angular.element("<div>").html(html).text();
// post filter
var filter = attrs.postFilter;
var result = $filter(filter)(text);
// apending html
element.html(result);
};
});
The important bit is the text variable. Here I create an intermediate DOM element and append it the HTML using the html method and then retrieve only the text with the text method. Both methods are provided by Angular's lite version of jQuery.
The following part is applying the newline filter, which is done using the $filter service.
Check the plunker here: http://plnkr.co/edit/SEtHH5eUgFEtC92Czq7T?p=preview
An update to the filter with ng-bind-html currently would be:
myApp.filter('newlines', function () {
return function(text) {
return text.replace(/(
)?
/g, '<br/>');
}
});
and the noHTML filter is no longer required.
white-space solution is having low browser support:
http://caniuse.com/#search=tab-size
Bit late to the party on this but I would suggest a small improvement to check for undefined / null strings.
Something like:
.filter('newlines', function () {
return function(text) {
return (text) ? text.replace(/(
)?
/g, '<br/>') : text;
};
})
Or (bit tighter)
.filter('newlines', function () {
return function(text) {
return (text instanceof String || typeof text === "string") ? text.replace(/(
)?
/g, '<br/>') : text;
};
})
I'm using the jQuery Quicksand plugin. I need to get the data-id of the clicked item and pass it to a webservice.
How do I get the data-id attribute? I'm using the .on() method to re-bind the click event for sorted items.
$("#list li").on('click', function() {
// ret = DetailsView.GetProject($(this).attr("#data-id"), OnComplete, OnTimeOut, OnError);
alert($(this).attr("#data-id"));
});
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<ul id="list" class="grid">
<li data-id="id-40" class="win">
<a id="ctl00_cphBody_ListView1_ctrl0_SelectButton" class="project" href="#">
<img src="themes/clean/images/win.jpg" class="project-image" alt="get data-id" />
</a>
</li>
</ul>
To get the contents of the attribute data-id (like in <a data-id="123">link</a>) you have to use
$(this).attr("data-id") // will return the string "123"
or .data() (if you use newer jQuery >= 1.4.3)
$(this).data("id") // will return the number 123
and the part after data- must be lowercase, e.g. data-idNum will not work, but data-idnum will.
If we want to retrieve or update these attributes using existing, native JavaScript, then we can do so using the getAttribute and setAttribute methods as shown below:
Through JavaScript
<div id='strawberry-plant' data-fruit='12'></div>
<script>
// 'Getting' data-attributes using getAttribute
var plant = document.getElementById('strawberry-plant');
var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'
// 'Setting' data-attributes using setAttribute
plant.setAttribute('data-fruit','7'); // Pesky birds
</script>
Through jQuery
// Fetching data
var fruitCount = $(this).data('fruit');
OR
// If you updated the value, you will need to use below code to fetch new value
// otherwise above gives the old value which is intially set.
// And also above does not work in ***Firefox***, so use below code to fetch value
var fruitCount = $(this).attr('data-fruit');
// Assigning data
$(this).attr('data-fruit','7');
Read this documentation
Important note. Keep in mind, that if you adjust the data- attribute dynamically via JavaScript it will not be reflected in the data() jQuery function. You have to adjust it via data() function as well.
<a data-id="123">link</a>
JavaScript:
$(this).data("id") // returns 123
$(this).attr("data-id", "321"); //change the attribute
$(this).data("id") // STILL returns 123!!!
$(this).data("id", "321")
$(this).data("id") // NOW we have 321
If you are not concerned about old Internet Explorer browsers, you can also use HTML5 dataset API.
HTML
<div id="my-div" data-info="some info here" data-other-info="more info here">My Awesome Div</div>
JavaScript
var myDiv = document.querySelector('#my-div');
myDiv.dataset.info // "some info here"
myDiv.dataset.otherInfo // "more info here"
Demo: http://html5demos.com/dataset
Full browser support list: http://caniuse.com/#feat=dataset
You can also use:
<select id="selectVehicle">
<option value="1" data-year="2011">Mazda</option>
<option value="2" data-year="2015">Honda</option>
<option value="3" data-year="2008">Mercedes</option>
<option value="4" data-year="2005">Toyota</option>
</select>
$("#selectVehicle").change(function () {
alert($(this).find(':selected').data("year"));
});
Here is the working example: https://jsfiddle.net/ed5axgvk/1/
This piece of code will return the value of the data attributes. For example: data-id, data-time, data-name, etc.
I have shown it for the id:
Click
JavaScript: Get the value of the data-id -> a1
$(this).data("id");
JQuery: This will change the data-id -> a2
$(this).data("id", "a2");
JQuery: Get the value of the data-id -> a2
$(this).data("id");
HTML
<span id="spanTest" data-value="50">test</span>
JavaScript
$(this).data().value;
or
$("span#spanTest").data().value;
ANS: 50
Accessing the data attribute with its own id is a bit easy for me.
$("#Id").data("attribute");
function myFunction(){
alert($("#button1").data("sample-id"));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="button1" data-sample-id="gotcha!" onclick="myFunction()"> Clickhere </button>
var id = $(this).dataset.id
works for me!
I use $.data:
//Set value 7 to data-id
$.data(this, 'id', 7);
//Get value from data-id
alert( $(this).data("id") ); // => outputs 7
Using jQuery:
$(".myClass").load(function() {
var myId = $(this).data("id");
$('.myClass').attr('id', myId);
});
Try
this.dataset.id
$("#list li").on('click', function() {
alert( this.dataset.id );
});
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<ul id="list" class="grid">
<li data-id="id-40" class="win">
<a id="ctl00_cphBody_ListView1_ctrl0_SelectButton" class="project" href="#">
<img src="themes/clean/images/win.jpg" class="project-image" alt="get data-id >>CLICK ME<<" />
</a>
</li>
</ul>
for pure js
let btn = document.querySelector('.your-btn-class');
btn.addEventListener('click',function(){
console.log(this.getAttribute('data-id'));
})
The issue is you are not specifying the option or selected option of dropdown or list, Here is an example for dropdown, i am assuming a data attribute data-record.
$('#select').on('change', function(){
let element = $("#visiabletoID");
element.val($(this).find(':selected').data('record'));
});
For those looking to dynamically remove and re-enable the tooltip, you can use the dispose and enable methods. See .tooltip('dispose').
HTML 5 introduced dataset: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset, the browser compa
But for older browser you can use getAttribute method to get the data-* attributes.
const getDataAttr = (id) => {
if(currentNode.dataset) return currentNode.dataset[id];
return currentNode.getAttribute("data-"+id);
}
The reason to use dataset is constant lookup time, get attribute would not be a constant time lookup, it'll go through all the attributes of the html element and then return the data once it'll find the exact attribute match.
The reason to provide this answer is that nobody mentioned about the browser compatibility and lookup time with the given solution, although both of these solutions are already given by people.
I have a span. I want to take the value of attribute data-txt-lang, which is used defined.
$(document).ready(function ()
{
<span class="txt-lang-btn" data-txt-lang="en">EN</span>
alert($('.txt-lang-btn').attr('data-txt-lang'));
});