Jquery select specific element - php

I have a list of radio tags with a diffrent id(post-1,post2 etc).
I am trying to preforme get request with the specific post id by clickign the radio.
This is the html:
$("#pro").click(function(){
var post = $(this).val();
alert(post);
$.get("<?php echo get_template_directory_uri(); ?>/jquery.php",{type: 'post', userid :'<?php echo get_current_user_id();?>', postid: '<?php echo $post->ID; ?>', pro : "pro"},function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
<input type = "radio" value = "<?php echo $post->ID;?>" class="pro-radio" name="pro-<?php echo $post->ID;?>" id="pro" <?php echo $GLOBALS['lock']; ?> <?php echo $pro_select; ?>> <label for="pro" class="pro-radio" >pro</label>
and this is the jquery:
When I press one of them, all of the radios oprate the jquery.
Thank you.

I think you reverted name and ids,
try this html
<input type = "radio" value = "<?php echo $post->ID;?>" class="pro-radio" id="pro-<?php echo $post->ID;?>" name="pro" <?php echo $GLOBALS['lock']; ?> <?php echo $pro_select; ?>> <label for="pro" class="pro-radio" >pro</label>

try adding a different class for each radio button and select by class name
var post = $('.className').val();
alert(post);

I think your HTML is a bit weird. You use the same id but different name attributes for your radios. Assume, you have this HTML:
<input type="radio" name="pro" value="1" id="pro-1"> <label for="pro-1">pro 1</label>
<input type="radio" name="pro" value="2" id="pro-2"> <label for="pro-2">pro 2</label>
<input type="radio" name="pro" value="3" id="pro-3"> <label for="pro-3">pro 3</label>
Then use this JS to get the selected value:
$('input[name=pro]').change(function() {
if ($(this).is(':checked')) {
alert($(this).val());
}
});
Please note, that the radios are selected by their (identical) name, but not by the (different) id. Then you have to verify the current element is the selected one using .is(':checked') and finally I use change() instead of click() if the element is selected via keyboard input.
Check it out here: http://jsfiddle.net/seofu1t4/

Related

PHP: why does whenever i edit it does not allow me to change the value in select box

whenever i select an option in my select box it automatically display the value in the text box in the create.php
here is the code of the create.php
<div class="form-group">
<label for="sub_category">Category:</label>
<select class="form-control select_group" id="sub_category_1" name="sub_category[]" onchange="getSubCategoryData(1)">
<option value=""></option>
<?php foreach ($sub_category as $k => $v): ?>
<option value="<?php echo $v['id'] ?>"><?php echo $v['name'] ?></option>
<?php endforeach ?>
</select>
</div>
<div class="form-group">
<label for="markup">Markup:</label>
<input type="text" class="form-control" id="markup" name="markup" disabled autocomplete="off" placeholder="Markup">
<input type="hidden" class="form-control" id="markup_value" name="markup_value" autocomplete="off">
</div>
then it's working fine just like i wanted to.
as you can see in this photo i the category is a select box and whenever i select an option the markup will be displayed based on the category data
script in create.php
function getSubCategoryData(row_id)
{
var sub_category_id = $("#sub_category_"+row_id).val();
if(sub_category_id == "") {
$("#markup").val("");
$("#markup_value").val("");
} else {
$.ajax({
url: base_url + 'products/getSubcatById',
type: 'post',
data: {sub_category_id : sub_category_id},
dataType: 'json',
success:function(response) {
$("#markup").val(response.markup);
$("#markup_value").val(response.markup);
}
});
}
}
bet when it comes to editing in a scenario of i want to change the category because i input an mistake data it does not process, in my edit.php wherein i can edit the fields in this module i can edit the name the cost and etc.. but i cannot edit the category whenever i try to change the category to others it does not allow me to click it and the markup value stays what value i have in the early data entry
example is that i have 2 category 1 is starter and 2 is drinks my first category has a markup of 50 and the second one is 60 so whenever i data entry an data and i want to change it's markup it does not allow me to change the category and my markup and i can't seem to know what is my problem here.
here is my edit.php code
<div class="form-group">
<label for="sub_category">Category:</label>
<?php $sub_category_data = json_decode($product_data['sub_category_id']); ?>
<select class="form-control select_group" id="sub_category_1" name="sub_category[]" onchange="getSubCategoryData(1)">
<?php foreach ($sub_category as $k => $v): ?>
<option value="<?php echo $v['id'] ?>" <?php if(in_array($v['id'], $sub_category_data)) { echo 'selected="selected"'; } ?>><?php echo $v['name'] ?></option>
<?php endforeach ?>
</select>
</div>
<div class="form-group">
<label for="markup">Markup:</label>
<input type="text" class="form-control" id="markup" name="markup" disabled
value="<?php echo !empty($this->input->post('markup_value')) ?:$product_data['markup'] ?>"
autocomplete="off" placeholder="Markup">
<input type="hidden" class="form-control" id="markup_value" name="markup_value"
value="<?php echo !empty($this->input->post('markup_value')) ?:$product_data['markup'] ?>"
autocomplete="off">
</div>
and the ajax or script in the edit.php:
function getSubCategoryData(row_id)
{
var sub_category_id = $("#sub_category_"+row_id).val();
if(sub_category_id == "") {
$("#markup").val("");
$("#markup_value").val("");
} else {
$.ajax({
url: base_url + 'products/getSubcatById',
type: 'post',
data: {sub_category_id : sub_category_id},
dataType: 'json',
success:function(response) {
$("#markup").val(response.markup);
$("#markup_value").val(response.markup);
}
});
}
}
and yes i can see the data input earlier if i input an category 1 with a markup with 50 it does save in the field but whenever i edit it and change the category i cannot click on the select box and the markup does not change.
Please watch this video:
https://drive.google.com/file/d/1lFNCyxoFegyTJNoULrSs59ZsYa_rjNs3/view?usp=sharing
i'm having a hard time clicking the category when i tried to change and the markup does not change
in case the video does not work here i uploaded it in yt
https://youtu.be/52SYwU8y30A
Your base_url should be declared as javascript variable. You can assign PHP base_url() to base_url variable like this
var base_url = "<?php echo base_url() ?>;
url: base_url + "products/getSubcatById",
OR you can directly add like this too without declaring javascript variable
url: "<?php echo base_url(); ?>products/getSubcatById",

select option to fetch other inputs

What Im trying to do is select item name where is ID and if item selected it automatically adds that item serial number to serial number input.
I think it should be used ajax maybe but I dont know how exactly.
Item Name:<br />
<div class="select-holder">
<i class="fa fa-caret-down"></i>
<?php
if($_items->count_items() == 0)
echo '<select name="item-name" disabled><option value="no">You need to add a item first</option></select>';
else{
echo '<select name="item-name" id="change-item">';
$items = $_items->get_items_dropdown();
while($item = $items->fetch_object()) {
echo "<option value=\"{$item->id}\">{$item->name} - {$item->serialnumber}</option>";
}
echo '</select>';
}
?>
</div>
Serial Number:<br />
<div class="ni-cont">
<input type="text" name="item-serialnumber" class="ni" disabled/>
</div>
I have also other inputs like description, price and etc.. to fetch these inputs with these values.
example: i need get data to my field from select option id (value)
<input type="text" name="item-serialnumber" value="<?php echo $_items->get_item_serialnumber($id); ?>" class="ni" disabled/>
<input type="text" name="item-serialnumber" value="<?php echo $_items->get_item_description($id); ?>" class="ni" disabled/>
That value is already shown inside your select-box you can simply use onchange event and then use $(this).find("option:selected").text().split('-')[1] this will give serial no then put it inside your input-box using $('[name=item-serialnumber]').val(somevalue) .Also ,you can send id via ajax to your server page and fetch result.
Demo Code :
$("#change-item").on("change", function() {
var value = $(this).find("option:selected").text().trim().split('-')[1]
$("[name='item-serialnumber']").val(value)
var id = $(this).val();
//use ajax :
$.ajax({
url: "somepgaename.php", //the page containing php script
type: "post", //request type,
dataType: 'json',
data: {
id: id //send id as well
},
success: function(data) {
console.log(data.yourfieldname);
//put inside your input fields values like :
// $("[name='item-serialnumber']").val(data.serialno)
}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Item Name:<br />
<div class="select-holder">
<i class="fa fa-caret-down"></i>
<select name="item-name" id="change-item">
<option value="1">Abc-123</option>
<option value="2">Abc2-122</option>
<option value="3">Abc2-132</option>
</select>
</div>
Serial Number:<br />
<div class="ni-cont">
<input type="text" name="item-serialnumber" class="ni" disabled/>
</div>
Then , at your server end get the id pass via ajax using $_POST['id'] then fetch result using select query and send them back to ajax using echo json_encode($somearray); i.e:
$id = $_POST['id'];
$stmt = $pdo->prepare("SELECT * FROM tablename WHERE id=:id");
$stmt->execute(['id' => $id]);
//put fetch result inside array..send back to ajax
//echo json_encode($somevalue);

PHP & MySQL query depends on checkboxes

I need some help with MySQL, jquery and PHP.
Here is my code :
HTML
<label class="checkbox"><input type="checkbox" name="code_site1" class="code_site1" checked="checked">Code 1</label>
<label class="checkbox"><input type="checkbox" name="code_site2" class="code_site2" checked="checked">Code 2</label>
<label class="checkbox"><input type="checkbox" name="code_site3" class="code_site3" checked="checked">Code 3</label>
<label class="checkbox"><input type="checkbox" name="code_site4" class="code_site4" checked="checked">Code 4</label>
Jquery
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideToggle("slow");
});
});
</script>
Everything here is working. But, I have an SQL query:
SELECT * from site;
I'd like to change it to :
SELECT * from site WHERE codeSite=$theOneThatIsChecked;
Actually, all I want is to establish a sql query depending on what is checked or note. For example, if code_site1 is checked, I'd like to have my SQL query like :
SELECT * from site WHERE codeSite=1;
That's pretty much I'm trying to do but I really don't know how to do it in PHP without submitting...
Can you help me ?
Thanks a lot !
EDIT:
First, thank you for your answsers. I tried the different solutions, but I still have an issue.
Actually, what I do :
- On my main page index.php I have an ajax script that points to "do.php" when I click on a submit button,
- On the "do.php" page I store a query depending on which checkboxes I have checked,
- Finally, thanks to :
success:function(data){
alert(data);
}
I can print the query that I made on "do.php". I'd like to know if I can store it in a php variable on my main page, in order to execute the query on my main page.
Thank you !
so if the request is sent correctly and no problem with that
you may change the name of checkboxes to name="code_site[]"
form example:
form should be like this if you want submit
<form method="POST">
<input type="checkbox" name="code_site[]" value="1">
<input type="checkbox" name="code_site[]" value="2">
<input type="checkbox" name="code_site[]" value="3">
<input type="checkbox" name="code_site[]" value="4">
<input type="submit">
</form>
with no submit:
$(document).ready(function(){
$("#flip").click(function(){
var data = { 'code_site[]' : []};
$("input:checked").each(function() {
data['code_site[]'].push($(this).val());
});
$.post("do.php", data);
});
});
then on the query side you can do
and because you are using checkbox so I assume that user can check multiple values, so you need to use "IN"
$codeSites = [];
if($_POST['code_site'])
$text = $_POST['code_site'];
$query = "select * from codeSite where codeSite in (" . implode($codeSites, ',') . ")";
echo $query; // use it
sure you need to do some input sanitization
or you can do this:
$codeSites = [];
if($_POST['code_site'])
$text = $_POST['code_site'];
$query = "select * from codeSite where codeSite in ('" . implode($codeSites, '\',\'') . "')";
echo $query; // use it
Use Ajax
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideToggle("slow");
if($('input[name="checkbox"]').is(':checked')){
var checkedValue =$("input[type='checkbox']").val();
var data ={id: checkedValue};
//make ajax request with the checked value
$.ajax({
url: url,
data:data
success: function(response) {
//process response
},
type: 'POST'
});
});
});
}
</script>
If I am understanding you correctly you will need to store the post value to a variable and the use that variable in your sql query
Change the input name so that they are all the same and then just add a value
Like this
<label class="checkbox"><input type="checkbox" value="1" name="code_site" class="code_site1" checked="checked">Code 1</label>
<label class="checkbox"><input type="checkbox" value="2" name="code_site" class="code_site2" checked="checked">Code 2</label>
And then something like:
if (isset($_POST['btn-checkbox'])){
$var = $_POST['codesite']
}
Then your query will be
SELECT * from site WHERE codeSite=$var;

I want to use PHP variable in jQuery in loop

I want to use PHP variable in jQuery.
I am having a 50 students data in table which having textbox and radio button.
By default textbox is hidden but when I clicked on radio button textbox show in table.
$("input[type='radio']").on('change', function() {
if ($(this).val() == "2")
var id = '<?php echo json_encode($absent); ?>';
//$("input[type='text']").show();
else
$("input[type='text']").hide();
});
PHP code:
<input name="nxtmark<?php echo $row[0]; ?>" type="text" id="nxtmark<?php echo $row['id']; ?>" onblur="onleave(this.name);" maxlength="2" placeholder="Enter Mark" hidden="" />
<div class="noerrordiv" id="dnxtmark<?php echo $row[0]; ?>">Mark must not be blank</div>
</td>
<td>
<div align="justify">
<input type="radio" id="rdopresent" name="rdopresent<?php echo $row['id']; ?>" checked="checked" value="1" />Present
<input type="radio" id="rdoabsent" name="rdopresent<?php echo $row['id']; ?>" value="2" />Absent<br />
</div>
</td>
</tr>
You can show / hide text box without using PHP variable. See below code -
$("input[type='radio']").on('change',function() {
//find input text from the previous 'td' for which name starts with 'nxtmark'
var $textBox = $(this).closest('td').prev('td').find('input[name^=nxtmark]');
//show hide text box as per radio button value
if($(this).val() == "2")
$textBox.show();
else
$textBox.hide();
});
If your Problem is just to use PHP variable in jquery then following examples will help you.
if you have to user a php array in jquery then use json_encode in PHP not in SCRIPT.
<?php
$a = array(1,2,3,4);
$a = json_encode($a);
$b = "hello";
?>
<script>
$(document).ready(function(){
alert("<?php echo $a; ?>");
alert("<?php echo $b; ?>");
});
</script>

Change a buttons value if parameters are met, jQuery, PHP, Sessions

I have the following button:
<input type="button" count='<?php echo count($_SESSION['children']);?>' name="children" class="add_child" value="Add Another Child"/>
On default when the form loads (with a clean session) there is no input for children, so the button should read "Add a Child".
If there is a text field present with the name children[] then it should just display: "Add another Child".
How would this be done ?
I am using php / jquery / sessions for the fields here is the code for it:
$('.add_child').click(function(){
var attrName = $(this).attr('name');
var count = $(this).attr('count');
$(this).attr('count', (parseInt(count)+1))
var input = $('<input />');
input.attr('type','text')
input.attr('name',attrName+"["+count+"]" )
$('.children_form').append($('<li />').append(input));
$('#content li:odd').addClass('alt');
})
<?php
if(isset($_SESSION['children'])) {
foreach($_SESSION['children'] as $index=>$child){ ?>
<li>
<?php echo "<input type='text' name='children[{$index}]' value='{$child}'/>";?>
</li>
<?php } }?>
Try this out with the code you have already:
$('.add_child').click(function(){
//code...
$(this).val('Add Another Child');
})
and the php for the input:
<input type="button" count='<?php echo count($_SESSION['children']);?>'
name="children" class="add_child"
value="<?php echo (isset($_SESSION['children'])?
'Add Another Child':'Add a Child');?>"
/>

Categories