javascript add onclick to html string - javascript

I got the following html string
<span class="text">North-West</span>
I need to add an onClick to this string in order to make it look like the following:
<span class="text" onClick="mySomeFunction()">North-West</span>
I tried to convert this string to jQuery element back and forth, or to use attr() or setAttribute() functions but it did not work. Any ideas how to do that would be welcome. Thank you.

If you are using jQuery, maybe you could put the event in your script file?
$('.text').on('click', mySomeFunction);
This way, you have your code organised in a file and it's a better practice. Inline JS is not very clean.

Without Jquery, using pure javascript:
Select your element
var t = document.querySelector('span');
Add your EventListener to detect the click
t.addEventListener('click', function(){
console.log('test');
someFunction();
})
var t = document.querySelector('span');
t.addEventListener('click', function(){
console.log('test');
alert('function');
})
<span class="text">North-West</span>

Here's an example:
html:
<button type="button" class="btn btn-primary" id="myConfirmButton">
Save changes
</button>
js:
var okbutton = document.getElementById("myConfirmButton");
okbutton.setAttribute("onclick", "deletedata('msgid',165);");

Related

JQuery get the title of a button

I have a button:
<button type="button" onclick="toggleColor('white');" >White</button>
Which makes this:
Is there any way to get what is written on the button using jQuery. For example this button would return White because its in-between the 2 button tags.
You can get it by using .text(),
$('button').text();
Please read here to know more about it.
add id to your button like this
<button type="button" onclick="toggleColor('white');" id="your_button_id" >White</button>
now you can use JS like this
var button_text = document.getElementById('your_button_id').innerHTML;
and also you can use JQUERY like this
var button_text = $('#your_button_id').text();
Try
$("button").click(function(){
var title=$(this).attr("value");
alert(title);
});
You can do this with Vanilla JS, after you've added an ID so you can fetch the element.
Assuming:
<button type="button" onclick="toggleColor('white');" id='myButton'>White</button>
You can do in JavaScript:
var someVar = document.getElementById('myButton').innerHTML; // -> White
var anotherVar = document.getElementById('myButton').textContent; // -> White
Both will hold "White"
give the button an ID
<button id="btnTest" type="button" onclick="toggleColor('white');" >White</button>
JQuery:
alert($("#btnTest").text());
Just provide one id to button and use it with JQuery
<button id=btn type="button" onclick="toggleColor('white');" >White</button>
then use jquery like this
$("#btn").val();
it will work for your condition.
Try this event.target
$("button").click(function(event){
var text=$(event.target).attr("value")
alert(text);
});
This worked for me on chrome.
$("#your-button-id").val();
If you prefer to use the Name= identifier (rather than id), you can get the button text by using:
$('button[Name="buttonNameHere"]').text();
and you can set the text by using:
$('button[Name="buttonNameHere"]').text("Replacement Text Here");
In Jquery you can use the following code:
$("#button").val();
The above line will give the text written on the button. And for setting text on the button through Jquery use the following code:
$("#button").val("SAVE");

Mixing razor syntax with Javascript in views

What's the proper way to go about it. I need it to work like in the example below.
<input type="button" value="Resume" onclick="window.location = '/Test?testid=#(ViewBag.TestID)'" />
I absolutely support Zabavsky's comment that you should use an ActionLink for this specific example in order to have semantically correct markup.
But since you asked:
Mixing razor syntax with Javascript in views
Never do that.
In your view you should have only markup:
<input type="button" value="Resume" id="myButton" data-url="#Url.Action("Test", new { testid = ViewBag.TestID })" />
and javascript (IN A SEPARATE FILE) where you could work with this markup and unobtrusively enhance it:
$(function() {
$('#myButton').click(function() {
window.location.href = $(this).data('url');
});
});
Of course if the user has javascript disabled your web application is completely busted. That's why you should always write semantically correct markup. In this case that would be to use an anchor because in HTML buttons are used to submit forms, anchors are used to redirect to some other location (which is exactly what you are trying to achieve in this specific case).
I would, as Zabavsky said, use an ActionLink for this:
Something like this:
#Html.ActionLink("Resume", "Test", new { testid = ViewBag.TestID })
There are quite a few overrides for actionlink, so you need to pick the one which fits your needs.
The one above output an a href with the text 'Resume' going to action 'Test' on the current controller, passing a routevalue of testid = ViewBag.TestID
You can do it like:
<html><head><script>function newDoc() { window.location.assign("http://www.abc.com") }</script></head><body><input type="button" value="Load new document" onclick="newDoc()"></body></html>
Hope it will help. Thanks.
Well, what you wrote is valid.
You may have VS underline your code in red cause it think you have a js error due to the '' string not ended... but if you run it, it works.
To avoid red underline, you could do :
#{string js = "window.location = '/Test?testid="+ViewBag.TestID+" '";}
<input type="button" value="Resume" onclick="#js" />

how to display text in div dynamically

I have searched on the forum and saw posts about changing text dynamically upon click. But in my case I want to change the display dynamically when loading the page from beginning. I already have a function that figure out what I should display:
function phone()
{
//code here
return phone;
}
And my question is how to display the returned phone number in the div below to replace the 1.888.888.8888 part. Can anyone offer some insights? Thank you!
<div class="add-info">
<span class="rightfloat">Order online <span class="red">or call 1.888.888.8888</span></span>
</div>
I would change the HTML to add another <span> tag around the phone number and give that span tag an id attribute in order to access it easily (broke it up on separate lines to reduce scrolling):
<div class="add-info">
<span class="rightfloat">
Order online <span class="red">
or call <span id="contact-number"></span>
</span>
</span>
</div>
Then after the page loads update the span with whatever value you want:
window.onload = function() {
document.getElementById('contact-number').innerHTML = PHONE_NUMBER_VALUE;
}
In JQuery, it would be:
$(document).ready(function () {
$('#contact-number').html(PHONE_NUMBER_VALUE);
});
You can,
<body onload="phone();">
<div class="add-info">
<span class="rightfloat">Order online <span class="red">or call
<span id="phone"></span>
</span>
</div>
</body>
And set the value when the function runs;
function phone() {
document.getElementById("phone").innerHTML = "1.888.888.8888";
}
Instead of returning 'phone', why don't you put an id on your span and just use
document.getElementById('spanId').innerHTML = phone
in your javascript?
Call you code from the window.onload event.
I would separate the number into additional <span> tag with its own id and change content of it with js...
document.getElementById('id_of_span').innerText = 'new number';
Try this
<script>
function phone(number) {
var redText = document.getElementByClassname("red")[0];
redText.innerHTML = "or call " + number;
}
</script>
To call it you can use clicks, loads or anything else. For example
<script>
window.onload = phone('NEW NUMBER HERE');
</script>
Bear in mind that adding another window onload function later will displace this one, so you would either need to add to it, or use a double delegate function, but that's another story...

Can't change onclick dynamically through javascript: bookmarklet

I've tried to change the onclick function through a bookmarklet in the url using this code:
javascript: document.getElementById('Button1').onclick = function(){alert('foo')};void(0);
I can change the value of the button but just not the onclick function. Is it even possible?
Thanks ^^
Some notes: I've also tried putting the code in a .js file and creating an external .js file using createElementId but it still does not seem to work :/
You were missing the trailing semi-colon to terminate the alert call. It's easier to spot once you indent it:
document.getElementById('Button1').onclick = function() {
alert('foo');
};
This code works. So the only option is that Button1 is not an ID of an element on that page.
For example:
<div id="Button1">Button</div>
If an element on the page looks like that, you will get your alert ('foo');
Your code seems to work...
Try to insert this code into the w3schools jseditor http://www.w3schools.com/js/tryit.asp?filename=tryjs_events
<html>
<body>
<button type="button" id="Button1" onclick="alert('Some action');">Action!!</button>
<button type="button" id="Button2" onclick="document.getElementById('Button1').onclick = function(){alert('another action')};">Change onclick</button>
</body>
</html>

jQuery replacement for onclick

I've just recently discovered the power of jQuery. Just a quick question though.
What is a replacement for onclick="DeleteSomething('THE ID NUMBER LOADED IN BY SERVER SIDE')" ?
Is there even a way somehow to pass custom information such as an ID to a jQuery onclick? Or do I have to stay with the old fashioned way?
I usually use a rel="" for some extra data i might need attached to the button or whatnot.
for example
<input class="btnDelete" rel="34" value="Delete" />
then in jquery
$('.btnDelete').click(function() {
DeleteMethod($(this).attr("rel"));
});
If you stick the ID of the object you want to delete in the rel parameter, you can do it this way:
<script type="text/javascript>
$('a.deleter').click(function(){
if($(this).attr("rel") != ""){
DeleteSomething($(this).attr("rel"));
}
});
</script>
Delete Widget
$(document).ready(function () {
$('#selector').click(function() {
//here goes your onclick code
});
);
Please, post some markup for more help.
Also, you should read the Getting started with jQuery resources, linked in the main page of the library.
In jQuery you would more likely do something like:
$('a').click(function(){
# code here
});
With 'a' being whatever selector you want to use to find the right link.
In response to your comment:
Probably the best way, as someone else mentioned, would be to provide the dynamic data in one of the attributes of the link:
<a rel="{id}" >
$('a').click(function(){
deleteFunction($(this).attr('rel'));
});
Instead of this:
<button onclick="DeleteSomething('THE ID NUMBER LOADED IN BY SERVER SIDE')">
Do this:
<button id="thing">
<script>
$(function() {
$("#thing").click(function() {
DeleteSomething('THE ID NUMBER LOADED IN BY SERVER SIDE');
}
}
<script>
It would much cleaner if you do it this way:
<tag class="someclass" prop1="id from serverside" />
$('.someclass').click(function(){
var prop1 = $(this).attr('prop1');
//DeleteSomething(prop1)
});
Use the server to replace {ID} with the actual ID.
HTML:
<form id="deleter">
<input type="hidden" name="id" value="{ID}" \>
<input type="submit" value="Delete" rel="{ID}" \>
</form>
jQuery:
$('form#deleter input[type="submit"]').click(function() {
var id = $(this).attr('rel');
DeleteSomething(id);
return false;
}
Don't forget to implement the deleting server-side also for people who don't have Javascript enabled!

Categories