How to set on click button value?
In my html form a set of users each having separate id. The users are auto generated, if new user register means they come into list.
Along with that i kept one button as "Invite". But this button id setting for whole users. If I kept on click button alert, it sets for whole users as alert msg.
EX:
If John as one user and have id as 5,if i click John's invite button means, for all users the alert is coming.
What I need is if John's invite I click means John only has to invited not all users.
How could I compare these user id and button id?
Here is a Code:
<script>
$(document).ready(function(){
$(".InviteTeacher").click(function(){
alert('Invited');
});
});
</script>
<div class="thumb_section bx-def-margin-sec-right">
__thumbnail__
</div>
<div class="button_wrapper">
<input type="button" value="Invite" name="InviteTeacher" class="InviteTeacher" id= "InviteTeacher"/>
</div>
Here thumbnail is a user information.
Store the values in hidden inputs.
<form>
<input type="hidden" name="from_id" value="1">
<input type="hidden" name="to_id" value="5">
<input type="submit" value="Invite">
</form>
At the place of generation buttons
$("#button" + userId).click(function(){
//do this
})
Suppose #invite0, #invite1, #invite2, ... are the html id attributes of the buttons to invite users[0],users[1],users[2],... and doInvite(j) is a function will invite the user at users[j].
You need to bind the current i value to the doInvite function, to get the actual handler.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
Note that doInvite(i) is wrong, that would invite them now, in the for loop, without pushing a button. And function(){ doInvite(i) } is wrong because i will have changed by the time the event handler is called.
But bind will create a new function for us with the loop value of i filled into the first parameter of the function. That can then be called as the event handler.
for(var i=0; i<users.length; ++i){
$('#invite'+i).click(doInvite.bind(null, i));
}
or this can also be written with a closure
for(var i=0; i<users.length; ++i){
$('#invite'+i).click( (function(j){
return function(){
doInvite(j);
}
})(i) );
}
in which case the loop value of i is stored in a new scope created by the top anonymous function, inside its j parameter. You can think of this nesting of anonoymos functions as returning slightly different event handler functions each time around the loop. The j's all exist in their own scopes, and store the values 0,1,2,3,... as the loop progresses.
For another example about closures and event handler setting in a loop, see Event handlers inside a Javascript loop - need a closure?
For more on what closures are and what they do see How do JavaScript closures work?
Related
I am building an ecommerce site on Wordpress to be used by multiple agents. At present, the page uses a standard PayPal link which includes the line:
<input type="hidden" name="business" value="somewhere#this-site.com">
My theory WAS that I could use PHP to get new user's business email address from my site, and then use javascript to change the value. For test purposes, I 'faked' the former, and so used this code ...
<script language="javascript">
// alert(document.getElementsByName('business').value);
document.getElementsByName('business').value='changed#paypal_address.com';
alert(document.getElementsByName('business').value);
</script>
IN THEORY, the page should now have a revised "business" field - but it stayed the same. So I added the second commented out alert ... which - when the page was reloaded - came back as 'undefined'
I cannot check data via forms as there are several (un-named) forms on the page, (such as form buttons with no action field that are used as delete items from cart buttons, and the PayPal webscr form which is also un-named)
Although the code is in a footer widget, I know it's loading / running as I get the alert pop ups. It also executes PHP code within the footer as it loads the page.
Is there a restriction whereby "hidden" fields cannot be found, or altered dynamically? If so, is there any work around?? (If all else fails, will have to contact the UltraCart pugin team to see if the business name can be set at source)
Try this:
function setValueForElementsByName(name, value) {
var elements = document.getElementsByName(name);
for(var e in elements) {
elements[e].value = value;
}
}
setValueForElementsByName('business', 'changed#paypal_address.com');
getElementsByName returns a NodeList. Therefore, you need to access individual items by index like
document.getElementsByName('business')[0].value
If you wish to modify multiple elements with the same name, simply iterate over them like
var elements = document.getElementsByName('business');
for(var i=0; i < elements.length; i++){
elements[i].value = ...;
}
document.getElementsByName('business')[0].value='changed#paypal_address.com';
alert(document.getElementsByName('business')[0].value);
<input type="hidden" name="business" value="somewhere#this-site.com">
I would like to be able to get as many properties from a button to show as I can.
The button:
<input name="Accept" type="submit" class="button" id="Accept" value="Accept" />
The button code:
if(isset($_POST['Accept'])){
//show button properties here
}
What I would like it to show on button press:
name: Accept
type: submit
class: button
id: Accept
value: Accept
and what ever else can be shown
Thank you in advanced.
One possible way, without using javascript would be to store a copy of the data in the name of the element:
<input name="Accept" type="submit" class="button" id="Accept" value="Accept" />
becomes:
<input name="Accept.submit.button.Accept" type="submit" class="button" id="Accept" value="Accept" />
You can get the value from your $_POST array. For the rest of the properties, just split up the key of the element using explode().
There is no way how to get properties of HTML element by normal HTML behavior - but you can use JavaScript function that handles "onSubmit" form event by which you can send all you need.
There is no way to submit properties of an input besides the name and value, however you can have hidden inputs on the form with whatever information you want, and you can even create them or populate them dynamically in the button's onclick even or the form's onsubmit event.
As another option I would stuff in the information in the button's value in JSON form, since the button's value usually anyway serves no purpose.
And if you are really out for ideas then you can stuff the info in the query string of the url in the action attribute of the form, and then get the info by checking the GET array (however if the form method is get instead of post then the values might get overwritten!)
But if yout problem is only that you need a way to distinguish between many buttons, then just have a different name or value for each of them, and this is probably the only reason why buttons have names and values.
Regarding andrejd's answer please note that while you can use the onSubmit function to to submit with Ajax and then return false to cancel the default submit, please note that the following problems exist with that approach:
1) That the onSubmit function doesn't know which button was pressed, however you can instead use the button's onClick event, but you will have to bind to every submit button on the form (you can do this much easier with jquery etc.)
2) Since Ajax does not affect the page content so ypu will refresh it on your own or navigate the page on your own, the latter can be done using "location.href"
3) If you are submitting files you will have a hard time doing it with ajax, you can try the use the jquery fileupload plugin.
4) Ajax is restricted to the same origin (something tgat form submittion isn't), you can try to workaround using JSONP.
5) Ajax will not work if the client doesn't have JavaScript (such as some mobile phones or some text browsers such as linux browsers) or has disabled JavaScript or is using an older browser, and in general it is not recommended to rely solely on Ajax but instead at least provide an alternative for these cases.
For problems 2-4 you can aldo solve them by having the Ajax just the extra content and then return true to let the default submission submit the form.
In my form there is a textbox and submit button. When a user starts typing, after the 3rd letter the autocomplete script does it's magic.
There are two possibilities.
The user types a word, there are matches and he clicks on one match. This selected match is added to the textbox and then hits the submit button.
The user types a word, there/there are not matches but he decides to hit the submit button without selecting one of the suggested.
My question is how can I identify whether he hit the button in case 1 or in case 2.
rpc.php is the file that looks for suggested values through the mySQL.
A solution is to check the string if there is on the database but I do not want this.
Another solution is to transform the jQuery script and php code that shows the product name and instead of putting the product in the textbox, it should take him to the results page. This solves my problem also.
<script type="text/javascript">
$().ready(function() {
$("#s").autocomplete("rpc.php", {
width: 250,
selectFirst: false,
minChars: 3,
scroll:true,
matchContains: true,
scrollHeight: 250
});
});
</script>
<form method="get" action=".php">
<input type="text" name="s" id="s" class="inputsearch">
<input type="submit">
</form>
Use autocomplete's change method to set a flag in the form, eg
/// Create an hidden element to store the flag value,
/// 1 for AC used, 0 for user entered
var flag = $("<input>").attr("type", "hidden")
.attr("name", "ac_flag")
.val(0);
// append flag to form
$("form").append(flag);
$("#s").autocomplete("rpc.php", {
change: function(event, ui) {
flag.val(ui.item != null ? 1 : 0);
},
// and the rest
});
The "change" event fires when the value in the text field changes. When an AC item is chosen ui.item will contain an object reference to the selected item from the list. If no selection was made, ie the user simply entered text, ui.item will be null.
Your form handler can then check for $_GET['ac_flag'] to determine whether or not the value came from the autocomplete list.
Quick mockup example here - http://jsfiddle.net/9GQgh/
The simplest approach would be to modify the autocomplete plugin itself to set a flag when the user chooses a value from it, and clear it when the user modifies their selection. The flag could be anywhere, but for the sake of simplicity I'd suggest a hidden form field, like:
<form method="get" action=".php">
<input type="text" name="s" id="s" class="inputsearch">
<input type="hidden" id="flag" name="inputCameFromAutocomplete" value="false">
<input type="submit">
</form>
So in the autocomplete plugin, when the user makes a selection, you could add something like:
$("#flag").val("true");
If you wanted to you could make the id/selector of the flag element part of the plugin config/options so that it is more reusable.
You would also want to do something like:
$("#s").keypress(function() {
$("#flag").val("false");
});
...as part of your initial setup, so that the flag is reset whenever the user manually types something into the field.
Just want to know if there is a way to detect how many times a user has clicked a button by using Jquery.
My main application has a button that can add input fields depend on the users. He/She can adds as many input fields as they need. When they submit the form, The add page will add the data to my database. My current idea is to create a hidden input field and set the value to zero. Every time a user clicks the button, jquery would update the attribute of the hidden input field value. Then the "add page" can detect the loop time. See the example below.
I just want to know if there are better practices to do this. Thanks for the helps.
main page
<form method='post' action='add.php'>
//omit
<input type="hidden" id="add" name="add" value="0"/>
<input type="button" id="addMatch" value="Add a match"/>
//omit
</form>
jquery
$(document).ready(function(){
var a =0;
$("#addMatch").live('click', function(){
//the input field will append //as many as the user wants.
$('#table').append("<input name='match"+a+"Name' />");
a++;
$('#add').attr('value', 'a'); //pass the a value to hidden input field
return false;
});
});
Add Page
$a=$_POST['a']; //
for($k=0;$k<$a;$k++){
//get all matchName input field
$matchName=$_POST['match'.$k.'Name'];
//insert the match
$updateQuery=mysql_query("INSERT INTO game (team)
values('$matchName')",$connection);
if(!$updateQuery){
DIE('mysql Error:'+mysql_error());
}
}
I'm a bit confused. After this:
$('#add').attr('name', 'a'); //pass the a value to hidden input field
shouldn't you actually store the value of a?
$('#add').attr('name', 'a').val(a);
$('#add').attr('name', 'a').val(a); ????
That's not correct, you should use:
$('#add').attr('value', a);
send the content of the "a" variable to the "value" property of element with ID "add"
I do believe that's what you want to do....
i have a list of names with "delete" button, every row is a form and clicking on delete the list should be updated in real time but don't works because in this plugin i can set only one id (infact it runs when in the list there's only one name)
this is the javascript function:
$(document).ready(function() {
var options = {
target: '#risposta',
resetForm: true,
success: function(showResponse) {
$("#lista_categorie").load("categorie.php").show('fast');
$('#risposta').fadeIn(2000),setTimeout(function({$('#risposta').fadeOut(1000);},5000);}};
$('#elimina_categoria').ajaxForm(options);
});
the html form is build with php:
<form action="categorie_elimina.php?id=$row['id']" method="post" id="elimina_categoria">
<p>$row['nome']
<input type="submit" id="submit_pro" value="elimina" class="elimina"></p>
</form>
i should create a different id for every form (using the id of the row for example) but i should tell to js function that every form must follow that function in this line:
$('#elimina_categoria').ajaxForm(options);
i also used this code:
$('[id|=elimina_categoria]').ajaxForm(options);
but this only works at first click, clicking the second time it opens the php script..
hope you can help me, sorry for bad english
First of all:
Instead of creating several forms with the same id, you should create several forms with the same class. The same value for the ID-attribute should only be used once. Example
<form id="elimina_categoria_1" class="elimina_categoria"> ... </form>
<form id="elimina_categoria_2" class="elimina_categoria"> ... </form>
Please use a more descriptive naming than _1, _2 ... though, if possible.
When each form has the same class, you can call ajaxForm(options) using
$('form.elimina_categoria').ajaxForm(options)
Second:
The script you're probably looking for is something like this
function eliminaCategoria() {
var eliminaForm = $(this).parent().parent(); // Select the form of the button
$.post(eliminaForm.val('action')); // Call the action defined by the form
eliminaForm.remove(); // Remove the form-element from the page.
return false; // don't let the submit-button submit the form.
}
$(document).ready( function() {
$('.elimina').bind('click', eliminaCategoria);
});
The script might not work as-is in your current situation, but I hope this helps you forward. You probably want add the fadeIn, fadeOut effects you used and you might want to check the results of the HTTP POST request before deleting the form from the page.