Reputation: 171
I am little confused about if condition in jQuery. I want to put 'if' condition into a jQuery function. Is this right way? Or any other solution better than this?
I want this method put into below jQuery function - how can I achieve it?
if($(this).attr("id")=='emptys'){
data = { msg : datas } //this is element inside of ajax
}
else{
data = { pid : datas } //this is element inside of ajax
}
I want this method put in below function
<script>
$(document).ready(function(){
$('.but').click(function(){
var datas = $(this).attr("id");
$.ajax({
type: 'GET',
url:"addcart.php",
data : { pid : datas },
success:function(result){
$("#div1").html(result);
}});
});
});
</script>
Upvotes: 1
Views: 271
Reputation: 664
<script>
$(document).ready(function(){
$('.but').click(function(){
var datas = $(this).attr("id");
if(datas =='empty'){
data : { msg : datas } //this is element inside of ajax
}
else{
data : { pid : datas } //this is element inside of ajax
}
$.ajax({
type: 'GET',
url:"addcart.php",
data : data,
success:function(result){
$("#div1").html(result);
}});
});
});
</script>
Upvotes: 0
Reputation: 388316
Try
$(document).ready(function () {
$('.but').click(function () {
var data;
if (this.id == 'empty') {
data = {
msg: datas
}
} else {
data = {
pid: datas
}
}
$.ajax({
type: 'GET',
url: "addcart.php",
data: data,
success: function (result) {
$("#div1").html(result);
}
});
});
});
or a better
$(document).ready(function () {
$('.but').click(function () {
var data = {};
data[this.id == 'empty' ? 'msg' : 'pid'] = this.id
$.ajax({
type: 'GET',
url: "addcart.php",
data: data,
success: function (result) {
$("#div1").html(result);
}
});
});
});
Upvotes: 3
Reputation: 10378
<script>
$(document).ready(function(){
$('.but').click(function(){
var datas = $(this).attr("id");
var tempdata;
if(datas ==''){// if empty then check by ""
tempdata= { msg : datas } //this is element inside of ajax
}
else{
tempdata= { pid : datas } //this is element inside of ajax
}
$.ajax({
type: 'GET',
url:"addcart.php",
data : tempdata,
success:function(result){
$("#div1").html(result);
}});
});
});
</script>
Upvotes: 1