jQuery replacement for onclick - javascript

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!

Related

Problems with getElementById with jquery load

I have a page, showlist.php, which loads a set of results from a recordset. There is a search field which returns results using jquery load. This works fine for one word, but not if there is more than one word in the search query. Can anybody show how to get this to work for any search query? Must be some basic error but googling around has not helped.
Key elements of showlist.php:-
<div id="contentarea">
<script type="text/javascript">
function contentloader(url){
$("#contentarea").load(url);
}
</script>
<input name="search" type="text" id="inputsearch"/>
<a onclick="contentloader('showlist.php?search='+document.getElementById('inputsearch').value+'')">Search</a>
</div>
You need to HTML encode the result of document.getElementById('inputsearch').value so that all the works are passes to the server.
See:
HTML-encoding lost when attribute read from input field
Encode URL in JavaScript?
and links therein.
You need to call encodeURIComponent with the value to correctly format the query/search term:
<a onclick="contentloader('showlist.php?search='+encodeURIComponent(document.getElementById('inputsearch').value)+'')">Search</a>
See Stack Overflow question Best practice: escape, or encodeURI / encodeURIComponent for further discussion.
type abc%20xyz in the box. if that works, maybe you need to urlencode the value.
You can use onClick listener, since you are already using jQuery. I think it is a better than using onClick attribute.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<div id="contentarea">
<input name="search" type="text" id="inputsearch"/>
<a id="search">Search</a>
<script type="text/javascript">
$( document ).ready(function (){ // when document ready
$("#search").click(function(){ // add a click listner
$("#contentarea").load(
encodeURI($('#inputsearch').val()) // encode input string
);
}
);
})
</script>
</div>

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 do I get HTML button value to pass as a parameter to my javascript?

I have multiple buttons corresponding to multiple text areas to clear. I need to send to have a function to handle all of these buttons and handle each seperately
<html>
<head>
<script src="jquery-1.6.js"></script>
<script type="text/javascript">
function getUniqueButtonValue(value)
{
alert(value);
$("value").hide();
}
</script>
</head>
<body>
<button id=someUinqueId value=something>Clear Selection</button>
</body>
</html>
Setting aside the fact that you're placing a unique id in the value attribute rather than the id attribute... here's a fiddle.
$(document).ready(function(){
$("button").click(function(){
var me = $(this);
// do whatever with me
alert(me.val());
me.hide();
});
});
There seem to be numerous problems with the code you've posted in your question. Firstly, (unless you're using <!DOCTYPE html> as your doctype) you can't have id values starting with a number.
Secondly, the jQuery (I'm assuming it's jQuery and not some other JS library) in your getUniqueButtonValue function is not going to work, because the selector is going to look for a value element, which is unlikely to exist.
I'm assuming that the value attribute of your button is meant to correspond to the id of another element, which you want to hide when the button is clicked.
As you have what appears to be jQuery code in your example, I will give you a jQuery solution to this, as it's far simpler:
$(document).ready(function() {
$("button").click(function() {
alert(this.value);
$("#" + this.value).hide();
});
});
Also, you don't close your body tag, but I'm guessing that's just a mistake in copying and pasting the code into the question.
You can do this:
<button id=123 value=uniqueId545 onclick="javascript:getUniqueButtonValue($(this).val());">Clear Selection</button>
try this
$("#123").click(function(){
getUniqueButtonValue($(this).val());
});
I'm not sure what you are trying to do here. If i guess correctly this is what you want (ids shouldn't begin with a number so I put an 'a' before the 123:
$("#a123").click(function(){
getUniqueButtonValue($("#a123").getAttribute('value');
}
function getUniqueButtonValue(value)
{
alert(value);
$("#"+value).hide();
}
</script>
</head>
<body>
<button id=123 value=uniqueId545>Clear Selection</button>
</html>
You can save yourself a lot of work by trying:
<button class="clearbutton" value="#Foo">Clear Foo</button>
<input type="text" name="foo" id="foo" />
With the following JavaScript:
$('.clearbutton').click(function(e) {
$($(this).val()).val('');
});

JavaScript doesn't work in Mozilla Firefox

I wrote the following code:
<form name=f>
<input type=button value="Button1" onclick=b1click()>
<input type=button value="Buttone2" onclick=b2click()>
<script language=javascript>
function b1click()
{
f.action="Login.jsp";
f.submit();
}
function b2click()
{
f.action="Logout.jsp";
f.submit();
}
</script>
</form>
This works code properly in Internet Explorer but the action does not work in Mozilla Firefox 3.6.2. How to solve this problem? Please any one help me.
I know this will sound snide, but the truth of the matter is: it's not 1995 anymore.
That code would have worked great a decade ago, but standards and specifications have changed significantly since then.
Lets start from the top:
<form name=f>
All html attribute values should be enclosed in quotes. For consistency sake, use double quotes: <form name="f"> is much better.
<input type="button" value="Button1" onclick="b1click()">
Avoid inline-script events. If the functionality ever changes, or you want to remove a function, you'll have to go through every page and adjust the function. A better way is to give the button an ID, and add the onclick event via scripts:
HTML:
<input type="button" value="Button1" id="button1">
JS:
document.getElementById('button1').onclick = b1click;
Now the script's turn:
<script language=javascript>
You should use the type attribute with a valid MIME type. Additionally, whenever possible, move your scripts to an external script file. When that's not possible, make sure to either XML encode your script, or encase it in CDATA tags:
<script type="text/javascript" src="path/to/script.js"></script>
OR
<script type="text/javascript">
/* <![CDATA[ */
... some code ...
/* ]]> */
</script>
Finally the real issue with your script.
The f property you're referencing is a member of the document, and not the window. I believe IE will put the reference on both, but it's just not safe to rely on either behavior.
Give the form an ID: <form id="f">, and get the element from the b[12]click functions
function b1click()
{
var f = document.getElementById('f');
f.action = 'Login.jsp';
f.submit();
}
First off, change that name="foo" to id="foo". Names are mostly used within the form itself.
Now, try to reference your form using document.formID, not just formID. formID is a variable, which is undefined, but document.formID is the actual form element:
function b1click()
{
document.f.action="Login.jsp";
document.f.submit();
}
function b2click()
{
document.f.action="Logout.jsp";
document.f.submit();
}
Give form an id and refer to it using:
var form = document.getElementById('formId');
You should quote the input attributes, or any attributes for that matter. And your script does not belong AFTER the form, e.g. in body, but rather in the HEAD element.
This works in IE, Firefox and Chrome.
<html>
<head>
<script language="javascript">
function b1click()
{
f.action="Login.jsp"; // better is document.f., but f. appears to work as well
f.submit();
}
function b2click()
{
f.action="Logout.jsp";
f.submit();
}
</script>
</head>
<body>
<form name="f">
<input type="button" value="Button1" onclick="b1click()">
<input type="button" value="Buttone2" onclick="b2click()">
</form>
</body>
</html>
There are a couple ways to reference your form.
If you define your form as <form name="Login" id="LoginFrom"></form>,
Method 1
If your form is the only one in the page, you can use:
document.forms[0].action = 'Login.jsp';
Method 2
If your form is not the only one form in the page, you can use the form name to reference the form, such as
document.Login.action = 'Login.asp';
Method 3
The form can also be referenced with DOM function getElementByID.
document.getElementByID('LoginForm').action = 'Login.asp'

How to focus on a form input text field on page load using jQuery?

This is probably very simple, but could somebody tell me how to get the cursor blinking on a text box on page load?
Set focus on the first text field:
$("input:text:visible:first").focus();
This also does the first text field, but you can change the [0] to another index:
$('input[#type="text"]')[0].focus();
Or, you can use the ID:
$("#someTextBox").focus();
You can use HTML5 autofocus for this. You don't need jQuery or other JavaScript.
<input type="text" name="some_field" autofocus>
Note this will not work on IE9 and lower.
Sure:
<head>
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$("#myTextBox").focus();
});
</script>
</head>
<body>
<input type="text" id="myTextBox">
</body>
Why is everybody using jQuery for something simple as this.
<body OnLoad="document.myform.mytextfield.focus();">
Think about your user interface before you do this. I assume (though none of the answers has said so) that you'll be doing this when the document loads using jQuery's ready() function. If a user has already focussed on a different element before the document has loaded (which is perfectly possible) then it's extremely irritating for them to have the focus stolen away.
You could check for this by adding onfocus attributes in each of your <input> elements to record whether the user has already focussed on a form field and then not stealing the focus if they have:
var anyFieldReceivedFocus = false;
function fieldReceivedFocus() {
anyFieldReceivedFocus = true;
}
function focusFirstField() {
if (!anyFieldReceivedFocus) {
// Do jQuery focus stuff
}
}
<input type="text" onfocus="fieldReceivedFocus()" name="one">
<input type="text" onfocus="fieldReceivedFocus()" name="two">
HTML:
<input id="search" size="10" />
jQuery:
$("#search").focus();
Sorry for bumping an old question. I found this via google.
Its also worth noting that its possible to use more than one selector, thus you can target any form element, and not just one specific type.
eg.
$('#myform input,#myform textarea').first().focus();
This will focus the first input or textarea it finds, and of course you can add other selectors into the mix as well. Handy if you can't be certain of a specific element type being first, or if you want something a bit general/reusable.
This is what I prefer to use:
<script type="text/javascript">
$(document).ready(function () {
$("#fieldID").focus();
});
</script>
place after input
<script type="text/javascript">document.formname.inputname.focus();</script>
The line $('#myTextBox').focus() alone won't put the cursor in the text box, instead use:
$('#myTextBox:text:visible:first').focus();
$("#search").focus();
You can also use HTML5 element <autofocus>
The Simple and easiest way to achieve this
$('#button').on('click', function () {
$('.form-group input[type="text"]').attr('autofocus', 'true');
});

Categories