Best way to code a big one-click toggle button to replace a single checkbox and submit button form?
I've got a page that has a simple one checkbox form with a submit button for users to mark that item as "want to play."
Given the simplicity, I'd like to replace it with a single DIV and graphic of a toggle button or switch or something, so that users can click it to mark, but not have to bother with the silly single checkbox and submit button, which is rather ugly.
The short and quick solution I can think of is for the div to be a link l开发者_C百科ike
markme.php?id=XYZ&user=123
that pops the flag into the database for that user and then redirects back to the page they were viewing.
Would that be reasonable? Is there a better way?
/me is an enthusiastic beginner
Make it a <button>
which has an onclick
event bound to it that performs an AJAX request to submit the request to some page handler that will update the database or similar, and on successful completion changes its CSS style to make it look pressed.
Use jQuery for the event binding, AJAX request, and CSS class changing, and this style should work to make the button look depressed.
<button type="button" id="btnPlay">Play</button>
Then:
$("#btnPlay").click(function(){
var button = $(this) ;
if (!button.hasClass('pressed')) {
//button is unpressed
$.post("ajax.php", { userId: "5512", action: "play" },
function(data){
button.addClass('pressed');
button.html("Playing!") ;
}
);
}
else {
//button is pressed, toggle it back
$.post("ajax.php", { userId: "5512", action: "stopPlaying" },
function(data){
button.removeClass('pressed');
button.html("Play") ;
}
);
}
});
精彩评论