2

I do have a simple script which is not working properly or as expected.

<script>
function modify_val(target, valeur)
{
    $(target).val(valeur)
}
</script>


<a href="javascript:modify_val('#type1','$row->movie2');">$row->movie2 ($row->counter relations)</a>

The javascript is working properly as the targeted input value is modified but the page is "redirected" after the click with a page containing:

[object Object]

Why is there a print ? I don't understand... The OnClick method behave the same. href or OnClick="javascript:$('#type1').val('$row->movie2');" also behave the same.

Do you have any idea ?

PS : the page is in https mode.

user1998000
  • 175
  • 1
  • 10

3 Answers3

1
<a href=\"javascript:$('#type1').val('$row->movie2'); void(0);\"> 

works... Guessing as Mate suggested that a return is mandatory

user1998000
  • 175
  • 1
  • 10
1

The return value of an event handler determines whether or not the default browser behaviour should take place as well.

<script>
function modify_val(target, valeur)
{
    $(target).val(valeur);
    return false;
}
</script>

Change your HTML as. I would suggest you to use onClick attribute

<a href="#" onClick="return modify_val('#type1','$row->movie2');">$row->movie2 ($row->counter relations)</a>

Demo

Satpal
  • 132,252
  • 13
  • 159
  • 168
  • Just returning false won't help if you don't do anything with the return value. – JJJ Nov 17 '13 at 16:51
  • It's still discarding the return value. And you don't need to use `javascript:` in onclick. – JJJ Nov 17 '13 at 16:52
  • @Juhana not necessarily.You can use `javascript:` it simply evaluated expression.the only think you need to make sure is to return false.or you can even say `preventDefault ` – Deepak Ingole Nov 17 '13 at 16:55
  • @captain As I said, you don't *need* to use it. It doesn't do anything. – JJJ Nov 17 '13 at 16:58
0

You probably need to stop the default action of the link by passing the event object and calling preventDefault() or simply returning false from your inline event handler.

function modify_val(target, valeur) {
    $(target).val(valeur)
    return false;
}

See this post for info on returning false from an inline event handler: What's the effect of adding 'return false' to a click event listener?.


For the cleanest code, I'd recommend not using an inline event handler at all and simply use jQuery (which you seem to already have available) to install a click event handler and keep your code and HTML much more separate (generally considered a good practice). jQuery also allows you to return false from the event handler to prevent the default behavior.

See this article on Unobtrusive Javascript for more info on keeping your HTML and Javascript separate.

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979