Two identical pieces of jQuery behaving differently
I have a PHP loop that outputs a bunch of link开发者_StackOverflow中文版s, then each link has a href='javascript:$(\"#rnn\").val(" . $foo . ");$(\"#rnnNotifUnsub\").submit();'
What is it supposed to do is to pass a certain piece of info pertaining to that link, over to a hidden input in #rnnNotifUnsub. However, it doesn't even submit when I try it out. I tried running the code without passing the variable to the hidden input and it submitted but of course didn't do anything. That means my problem lies in $(\"#rnn\").val(" . $foo . ");
messing up the code.
Here's my form, just in case:
<form action="php/retailerNameNotifUnsub.php" id="rnnNotifUnsub" method="POST">
<input type="hidden" value="" name="retailerName" id="rnn"/>
<input type="hidden" value="<?php print(selfURL()); ?>" name="url"/>
</form>
I have an identical set of code for an identical form, just with different names, and that works perfectly. Although that passes a int as a variable rather than a string to the hidden input. Perhaps that's the problem?
if foo is a string you will need to escape to set the value correctly.
From:
$(\"#rnn\").val(" . $foo . ");
To:
$(\"#rnn\").val(\"" . $foo . "\");
Inline Javascript is a Bad Idea. It is hard to maintain and messy.
I would give your links a data-retailer
attribute and a class (I'll use retailer
). You could then use jQuery in a script
tag like the following.
$(document).ready(function(){
$('a.retailer').click(function(e) {
e.preventDefault();
$('#rnn').val($(this).data('retailer'));
$('#rnnNotifUnsub').submit();
});
});
Example link:
<a class="retailer" data-retailer="Some Name" href="#">Content</a>
If you are using " to print ( echo "hello world" ), Mark is right... Or...
href='javascript:$(\"#rnn\").val(\"" . $foo . "\");$(\"#rnnNotifUnsub\").submit();'
精彩评论