Jquery Radio button value not changing - php

Need some help, ive searched google and have no luck.
I am trying to update my radios-button's value in the div class "size-number". That value I want use it within the ajax request below. When i inspect element, the radio-button has the updated value of the button available but when i console.log it in jquery, it gives me the same initial value, despite which i pick. Ive tried setting the radio-buttons to checked="checked". Also i believe its a matter of the default value. Ive also tried input validation within jquery. In addition, ive attempted to reference the input ("input[name='radiobten']:checked") in jquery as well. any suggestions would very appreciated!
$(".size-number").click(function(){
var modelid = $("#modelval").attr('value');
console.log(modelid);
$.ajax({
url: '"Example API"',
data: [],
dataType: 'json',
type: "GET",
success: function(res){
var newarr = (res).filter(function(indx){
return indx.model_cat_id == modelid
});
console.log(newarr)
$('modelselect').slideToggle(200).html(res);
}});
});
<?php foreach ($brands as $brand){ ?>
<div class="search-select">
<i class="fas fa-chevron-down"></i>
<a href="/<?php echo $brand->full_slug.$urlSize; ?>">
<?php echo $brand->name; ?></a>
</div>
<?php
$slugCurrent = $brand->slug;
foreach ($models as $model){
if($model->brand_id == $brand->id){
if(is_null($model->model_cat_id)){?>
<div class="size-number" style="display: none;">
<?php echo $model->name; ?><input type="radio" id="modelval" name="radiobten" value="<?php echo $model->id?>"/>
</div>
<?php
}
}
}
}?>

You cannot have multiple element with same id i.e : modelval. This will always give you value of first radio button no matter which button you choose.Instead use class to get value of radio button.So ,onclick of div you can use $(this).find("yourclassname").attr('value') to get value of that particular button only.
Demo Code :
$(".size-number").click(function() {
//div->find closest modelval->value
var modelid = $(this).find(".modelval").attr('value');
console.log(modelid);
$.ajax({
url: '"Example API"',
data: [],
dataType: 'json',
type: "GET",
success: function(res) {
var newarr = (res).filter(function(indx) {
return indx.model_cat_id == modelid
});
console.log(newarr)
$('modelselect').slideToggle(200).html(res);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="size-number" >
Abc<input type="radio" class="modelval" name="radiobten" value="1"/>
</div>
<div class="size-number" >
Xyz<input type="radio" class="modelval" name="radiobten" value="2"/>
</div>

Related

Detect any change from PHP form without using submit button

I need help. Now I trying to create a function that can detect any change value from PHP form. Now I'm working using CodeIgniter. I explain more detail about this.
I making an e-commerce site. If the user in the cart page and changing the qty but the user not yet checkout and still want to browser more.... when the user has to change qty and press to another page. It will display pop up alert. This pop-up alert have a function to save the changing Qty. But if the user not changing anything. The pop-up alert should not show.
I already set this in the menu.
<?php echo form_open('order_products_execute', 'class="order_form"'); ?>
<?php include(VIEWPATH.'_order_parts.html') ?>
<div class="common_btn_area">
<input type="hidden" name="branch_id" value="<?php echo $branch_id; ?>">
<button type="button" class="add_cart_more">add more</button>
<button type="submit" class="common_save_btn confirmation">Order</button>
</div>
<?php echo form_close(); ?>
<!-- footer menu -->
<ul>
<li>
<a href="<?php echo base_url('top/'); ?>" class="footer_link" onclick="ExitCart('<?php echo base_url('top/'); ?>')" >
<span>Home</span>
</a>
</li>
<li>
<a href="<?php echo base_url('product/'); ?>" class="footer_link" onclick="ExitCart('<?php echo base_url('product/'); ?>')" >
<span>Product</span>
</a>
</li>
</ul>
and set the script
<script>
function ExitCart(link){
var $form = $('.order_form');
#code for compare previous value with changing value
$.ajax( {
type: $form.attr('method'),
url : "/buyer/ajax/compare_form_add_cart",
dataType : "json",
data : $form.serialize(),
success : function(resultdata) {
if(resultdata){
if(confirm("Do you want to save your changes?")){
#if confirm yes
$.ajax({
type: 'post',
url: '/buyer/Ajax/add_order_data_in_cart_session',
data: $('.order_form').serialize(),
dataType: 'json',
success: function(res, textStatus, xhr){
if(res.result) {
location.href = link;
} else {
$( "#loading_layer" ).css('display', 'none');
alert('Failed to save cart data. Please try again.');
}
}
});
}else{
#if confirm not
location.href = link;
};
}else{
return true;
}
}
});
}
</script>
When I implement this ajax code, sometimes the code is working. But sometimes it is not. Is there any code that can detect any change from the form. But without the press submit button.
in jQuery you can bind all the inputs changes
$('.order_form input').change(functon(){
var $form = $('.order_form');
#code for compare previous value with changing value
$.ajax( {
type: $form.attr('method'),
url : "/buyer/ajax/compare_form_add_cart",
dataType : "json",
data : $form.serialize(),
success : function(resultdata) {
if(resultdata){
if(confirm("Do you want to save your changes?")){
#if confirm yes
$.ajax({
type: 'post',
url: '/buyer/Ajax/add_order_data_in_cart_session',
data: $('.order_form').serialize(),
dataType: 'json',
success: function(res, textStatus, xhr){
if(res.result) {
location.href = link;
} else {
$( "#loading_layer" ).css('display', 'none');
alert('Failed to save cart data. Please try again.');
}
}
});
}else{
#if confirm not
location.href = link;
};
}else{
return true;
}
}
});
})
You need to make copies of your input fields for example
// Input Field (TEXT)
< input type="text" id="input1" value="Same Value" />
// Hidden Input for comparison
< input type="hidden" value="Same Value" />
at on click function, you should compare these fields like
function ExitCart(link){
// Get Input Value
var val = $.trim($('#input1').val());
// Get Reference Value from next input
var valChk = $.trim($('#input1').next().val());
if(val != valChk) {
YOUR CODE HERE
}
}

Toggle Checkbox and send query in background to update database

As soon as someone toggles a checkbox. I want a the value sent to a php page for it to update it in my database.
HTML:
<div class="form-group">
<div class="tg-optionbox">
<span>Promotional Video</span>
<span class="tg-iosstylcheckbox">
<input type="checkbox" id="video" name="video" value="video">
<label for="video"></label>
<div id="echo2"></div>
</span>
</div>
</div>
JQUERY:
$(document).ready(function(){
$("input[type=checkbox]").click(function () {
$.ajax({
type: "POST",
url: "get/update-feature.php",
data: {
value: $('input:checkbox:checker').val()
},
success: function(data) {
$('#echo2').html(data);
}
});
});
});
PHP:
<?
$sent_value = $_POST['value'];
if(isset($sent_value)){
//update database
echo "updated";
}else{
//update database
}
?>
Currently, my jquery doesn't work. How I need it:
They click the orange checkbox toggle
Jquery recognises this and sends the checkbox value to my php page
my php page gets the value and puts it in the database
instead of echo use "return true" if success else false in php code
$(document).ready(function(){
$("#video").click(function () {
$.ajax({
type: "POST",
url: "get/update-feature.php",
data: {
value: $('input[type=checkbox]').val()
},
success: function(data) {
$('#result').html(data);
}
});
});
});
<div class="form-group">
<div class="tg-optionbox">
<span>Promotional Video</span>
<span class="tg-iosstylcheckbox">
<input type="checkbox" id="video" name="video" value="video">
<label for="video"></label>
<div id="echo2"><p id="result"></p></div>
</span>
</div>
</div>
The error is in $('input:checkbox:checker').val() so the value is not sent to php file and the success method expects a return value in php. We need to use "return" instead of "echo"
Hope this can help you.
HTML: Not Changed
<div class="form-group">
<div class="tg-optionbox">
<span>Promotional Video</span>
<span class="tg-iosstylcheckbox">
<input type="checkbox" id="video" name="video" value="video">
<label for="video"></label>
<div id="echo2"></div>
</span>
</div>
</div>
JavaScript: Changed
Replaced: value: $('input:checkbox:checker').val() by: value: $(this).prop("checked") ? 1 : 0
You have to send the value of the clicked checkbox. So you must use $(this).
To get the value of the checkbox use .prop("checked"). If the returned value is true, then it is checked. If it is false, then it is not checked.
So if the checkbox is checked, 1 is sent. If not, 0 is sent
$(document).ready(function(){
$("input[type=checkbox]").click(function () {
$.ajax({
type: "POST",
url: "get/update-feature.php",
data: {
value: $(this).prop("checked") ? 1 : 0
},
success: function(data) {
$('#echo2').html(data);
}
});
});
});
PHP: Changed
If the value is equal to 1 or value equal to 0
<?php
$sent_value = $_POST['value'];
if(isset($sent_value)){
if ($sent_value == 1) {
echo "Checked" ;
}
else {
echo "Un Checked" ;
}
}
else{
echo "Error" ;
}
?>
Use .change() event handler :
$('input:checkbox').change(function () {
var name = $(this).val();
var check = $(this).attr('checked');
//Your Ajax code
});

Trying to hide specific div in jquery in php while loop

I have this form being outputted from a PHP while loop :
echo '<div id="postCont" class="postCont'.$pid.'" style="block;">
<div id="clLink">
<a id="clLink" href="'.$plink.'" target="_blank"" title="'.$ptitle.'">'.$ptitle.'</a>
</div>
<div id="clDate">Posted on '.$pdate.'</div>
<div id="clDesc">'.$pdesc.'</div>
<form method="post" class="ibadForm">
<input type="hidden" name="id" value="'.$pid.'">
<input type="hidden" name="hiddenBad" value="yes">
<input type="image" src="../img/bad.png" name="subBad" value="Bad" class="bad">
</form>
</div>';
I am trying to remove the individual .postCont when the ibadForm is clicked with jquery.
$(".ibadForm").submit(function(e) {
var url = "add_form.php";
var id = <?php echo $pid?>;
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function(data)
{
$('.postCont' + id).hide();
}
});
e.preventDefault();
});
It submits the form to add_form.php fine but doesn't hide the postCont. If I remove the id from the class then it hides all post Cont's. Can anyone tell me where I am going wrong?
You could use closest() to get the parent div then hide it using hide() method like :
$(".ibadForm").submit(function(e) {
var url = "add_form.php";
var id = <?php echo $pid?>;
var _this = $(this);
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function(data)
{
_this.closest('.postCont').hide();
}
});
e.preventDefault();
});
NOTE : You should store the $(this) object that refer to the clicked form in some variable (_this in my example) then use it inside the success callback since $(this) inside callback doesn't refer no more to the form, e.g :
_this.closest('.postCont').hide();
Hope this helps.

what makes isset null/empty

I have several places that's returning empty and I am not sure why.
One place is using ajax. When an user clicks on the radio button, the value Y or N is sent upon clicking the radio button. When I go to my controller and do echo $_POST['vote']; it is always returning an empty value.
var value = $(this).val();
$.ajax( {
type: "POST",
url: url,
data: {'vote':value},
success: function(data){
alert(data);
}
})
Another place is when i do an ajax upload on a file using a form. On change of the upload field, it always return empty as well. So when I tried isset$_POST[Image] I am always getting a blank. It sees that all my file upload instance is blank.
So what would be the cause of these blanks? I also tried $_GET doesn't help much.
*****[EDIT]*********
<form id="vote-form" action="/some/path?r=shop/vote" method="post">
<input id="ytvote" type="hidden" value="" name="vote[hot_not]">
<span id="vote_hot_not">
<input class="fire-toggle" value="Y" type="radio" name="Vote[hot_not]" data-radio-fx="Vote[hot_not]" style="display: none;"><a title=" " data-radio-fx="Vote[hot_not]" class="radio-fx" href="#"><span class="radio"></span></a>
<label style="display:inline" for="Vote_hot_not_0"><img src=" /images/site/red-hot-not.png" id="hot-i"> </label>
<!--input class… fire-toggle-->
<input class="fire-toggle" value="N" type="radio" name="Vote[hot_not]" data-radio-fx="Vote[hot_not]" style="display: none;"><a data-radio-fx="Vote[hot_not]" class="radio-fx" href="#"><span class="radio"></span></a> <label style="display:inline" for="Vote_hot_not_1"><img src=” /images/site/hot-not.png" id="not-i"></label></span>
</form>
Now in my fire-toggle I have:
$(".fire-toggle").click(function() {
var value = $(this).val();
var url = "<?php echo Yii::app()->createUrl('shop/vote');?>";
$.ajax( {
type: "POST",
url: url,
data: {'vote':value},
success: function(data){
alert(data)
}
})
});
So value actually gives me the expected value..
and here in the controller... I simplified everything down to this:
$pid =Yii::app()->request->getQuery('id');
$uid = yii::app()->user->user_id;
$model = PrototypeReview::model()->getUserVote($uid, $pid);//also tried hard code numbers
$response = $_POST['vote']; //there's nothing in here!
echo $_POST['vote'];

Jquery not considering new div that is added by Jquery + php + jquery

I have a php page where I add and delete items from database using Jquery + PHP + AJAX.
Now I am able to delete and add when that page loads for the first time.
Now if I first add an element; which in turn adds record to the DB and then updates the div that contains all the listing of divs.
Example:
<div id="all_items">
<div id= "item_1">
<a id="delete_link">...</a>
</div>
<div id= "item_2">
<a id="delete_link">...</a>
</div>
.... Upto Item n
</div>
Now I replace the div with id all_items.
Now I have jQuery at the bottom of the page which calls ajax on a tag of delete_link.
Situtation is:
When page is loaded I can delete any item from the list.
But if I page load i add new item first. (which will update all_items div) after that if I try to click on delete link. Jquery on click selector event is not fired and which in turn doesn't do delete ajax operation.
I couldn't figure out why this is happening.
Looking for some help here.
EDITED:
Sorry for not writing code earliar.
Following is the jQuery I am talking about.
<script type="text/javascript" >
var jQ = jQuery.noConflict();
jQ(function() {
jQ("#submit_store").click(function() {
var store_name = jQ("#store_name").val();
var dataString = 'store_name='+ store_name;
dataString += '&mode=insert';
if(store_name =='')
{
alert("Please Enter store Name");
}
else {
jQ.ajax({
type: "POST",
url: "<?php echo $mycom_url; ?>/store_insert.php",
data: dataString,
cache: false,
success: function(html){
jQ("#dvstoreslists").html(html);
document.getElementById('store_name').value='';
document.getElementById('store_name').focus();
}
});
}
return false;
});
jQ(".store_delete").click(function() {
var store_id = jQ(this).attr('id');
var id = store_id.split("_");
var dataString = 'store_id='+ id[2];
dataString += '&mode=delete';
var to_delete = "#store_list_" + id[2]
jQ.ajax({
type: "POST",
url: "<?php echo $mycom_url; ?>/store_insert.php",
data: dataString,
cache: false,
success: function(html){
jQ(to_delete).hide("slow");
}
});
return false;
});
});
</script>
So If on page load, I delete then delete on click jquery event is fired. But after adding new store and replacing div of stores with new div. then jQuery on click event is not fired.
My HTML is as below.
<div class="sbBox stores">
<form id="add_storefrm" name="add_storefrm" method="post" action="" >
<div class="dvAddStore">
<div class="dvName" id="store_list">
<input type="text" id="store_name" name="store_name">
<input type="hidden" value="addstore" id="mode" name="mode">
</div>
<div class="btnAddStore">
<input type="submit" name="submit_store" value="Add Store" id="submit_store">
</div>
</div>
<div id="dvstoreslists">
<?php
$query = "SELECT * FROM #__shoppingstore order by store_id desc;";
$db->setQuery($query);
$rows = $db->loadObjectList();
foreach($rows as $row)
{
echo "<div class=dvlist id=store_list_".$row->store_id ."><div class=dvStoreListLeft>";
echo "<div class='slname'><h3>" . $row->store_name . "</h3></div>";
?>
<div class="slDelBtn">
<p id = "p_store_<?php echo $row->store_id ; ?>">
<a id="store_delete_<?php echo $row->store_id ; ?>" class="store_delete" alt="Delete" onclick="DeleteStore(<?php echo $row->store_id ; ?>);" >
</a>
</p>
</div>
</div>
</div>
<?php } ?>
</div>
</form>
</div>
Sorry folks for not posting the code earliar.
the ID should always be unique so use class instead
in your case : <a id="delete_link">...</a> to <a class="delete_link">...</a>
When you replace the contents of #all_items any event handlers that were bound to any descendants will no longer exist. You can use event delegation, using the on method, to solve this:
$("#all_items").on("click", ".delete_link", function() {
//Do stuff
});
Notice that I'm using a class selector (.delete_link) instead of an ID selector for the links. It's invalid to have duplicate IDs in the same document.
Also note that the above will only work if you are using jQuery 1.7 or above. For older versions, use delegate instead:
$("#all_items").on(".delete_link", "click", function() {
//Do stuff
});
This works because DOM events bubble up the tree from their target. So a click on a link which is a descendant of #all_items will bubble up through all of its ancestors and can be captured when it reached #all_items.
use live() instead of .bind()
It seems you are trying to delete dynamically added delete_link so i think you should use
$('id or class').on(click,function(){});

Categories