Reputation: 307
simple question but i just wanna know if I have the javascript correct to be called when this input button is clicked. I cant use an id on this button tho. So how would i call a click event in javascript instead of using hte onclick im using currently.
<input type="button" class="text" value="@video.Text" onclick="@String.Format("videochange('{0}')",url);" />
Upvotes: 0
Views: 145
Reputation: 391
You can use two ways,
1- Pure javaScript:
<input type="button" class="text" value="@video.Text" />
<script>
buttons = document.getElementsByTagName( 'input' );
for( var i = 0; i < buttons.length; i++ )
{
Btn = buttons[i];
if( Btn.className == 'text' )
{
Btn.onclick = function()
{
/* [...] */
}
}
}
</script>
2- [ OR In jQuery ]
$('.text').click(function()
{
/* [...] */
});
Upvotes: 0
Reputation: 2951
If you can use jQuery, then a better approach would be to not have inline scripts at all (really considered bad form).
Try something like this, instead:
<input type="button"
class="text"
value="@video.Text"
data-url="@String.Format('{0}',url);" />
(broke it into separate lines for ease of readability ... also, depending on how the template renders, you may run into accidental issues of terminating strings improperly, which is why I changed the "{0}" to '{0}')
Now, in your javascript:
// when the dom is ready
$(function() {
$('.text').click(function(evt){
evt.preventDefault();
var url = $(this).data('url');
videochange(url);
});
});
This properly separates your roles and responsibilities... server-side code stays server-side, and provides the data to the view. The view/client-side scripting then handles view-side interaction, without messily trying to merge syntax between two different languages.
Upvotes: 0
Reputation: 24322
Try it like this,
<input type="button" class="text" value="@video.Text" />
$(".test[type='button']").click(function(e){
e.preventDefault();
videochange('url');
});
Upvotes: 1