I want to show the detailed address of a selected recipient name from a dropdown menu. So, if I choose address A, it will display the details of address A.
I'm already working on the code but the issue is it doesn't show the correct value, instead it shows the last record in the database. Here's the code:
Blade
<select class="address-detail form-control" id="address" name="address_detail" data-target=".detail-info-address">
<option value="option_select">Select Address</option>
#foreach($addresses as $address)
<option value="{{$address->id}}" data-show=".info-address">{{$address->recipient_name}}
</option>
#endforeach
</select>
<div class="detail-info-address">
<div class="info-address hide text-left">
<p>Recipient Name: {{$address->recipient_name}}</p>
<p>Contact Number: {{$address->contact_number}}</p>
<p>Address: {{$address->address}}</p>
<p>Address Note (optional): {{$address->address_note}}</p>
<p>Post Code: {{$address->post_code}}</p>
<p>Province: {{$address->province}}</p>
<p>City: {{$address->city}}</p>
<p>District: {{$address->district}}</p>
<br>
</div>
</div>
Controller
public function buynow($id) {
$addresses = Address_Delivery_Users::where('user_id', '=', Auth::user()->id)->get();
return view('/transactions/delivery', compact('addresses'));
}
Javascript
<script>
$(document).on('change', '.address-detail', function() {
var target = $(this).data('target');
var show = $("option:selected", this).data('show');
$(target).children().addClass('hide');
$(show).removeClass('hide');
});
$(document).ready(function(){
$('.address-detail').trigger('change');
});
</script>
Your problem is that the variable $address is defined in the foreach loop, therefore the last element of the loop will be set to $address.
Hence, your address block will always contain the attributes of the last address element. After initial rendering of the page, you are not able to display another address in the PHP variable $address.
It is important that you differnetiate between PHP which is server-side and JS which is client-side.
You will have to listen to the change event of the select and get the new data. There are two options for that.
You make an ajax request to your server and return the address-object and set all fields correspondingly.
In your foreach loop you add for every attribute of your address a data-<varaible_name> html attribute and onchange get all data- attributes and insert them in the correct fields of your address block.
I would recommend using Vue.js for this task. However if you are new and don’t have much experience at all you might try plain JS/Jquery at the moment.
Related
I have a question on how to populate a drop-down list depending on the value that is selected in another drop-down list.
I'm working with an MVC pattern and when the view loads, it already brings me two variables with the values I need. What are $tipohardware and $tiposoftware.
So I wouldn't need to call a .php file again to get the data, because it's already loaded.
My static drop-down list is:
<select id="producto" class="form-control" required>
<option value="">Seleccionar..</option>
<option value="1">Hardware</option>
<option value="2">Software</option>
</select>
And the dynamic drop-down list I want to populate depending on what is selected in the drop-down list "producto" is:
<select id="tipoproducto" name="tipoproducto" class="form-control">
</select>
I already have two variables that have the data of the tables, "tipo_hardware" and "tipo_software". What are $tipohardware and $tiposoftware.
So, for example, if I select the "Hardware" option in the drop-down list, the second drop-down list should be filled with the data of the variable $tipohardware.
On the other hand, if I select "Software" the drop-down list should be populate with the values of the variable $tiposoftware.
Here's my controller if you needed to.
<?php
namespace app\controllers;
use \app\models\Hardware;
use app\models\Software;
use app\models\TipoHardware;
use app\models\TipoSoftware;
use \Controller;
use \Response;
class IngresarProductoController extends Controller
{
public function actionIndex()
{
$softwares = Software::all();
$hardwares = Hardware::all();
$tiposoftware = TipoSoftware::all();
$tipohardware = TipoHardware::all();
Response::render("ingresarProducto", ["hardwares" => $hardwares,
"softwares" => $softwares, "tipohardware" => $tipohardware,
"tiposoftware" => $tiposoftware]);
}
}
I think I should call a php code in a javascript onchange function like:
$("#producto").on("change",function){
<?php
foreach($tipohardware as $tipohard) {
?>
<option value="<?php echo $tipohard->idtipo_hardware ?>"><?php echo
$tipohard->nombre_tipo_hardwarecol ?></option>
<?php
}
?>
}
});
But I dont know how I can continue with that,
Thanks for the help!
You are mixing frontend script with backend script, which does not work. Backend will build the entire page before the frontend starts doing it's thing. PHP creates the DOM and JavaScript manipulates the DOM after PHP spits it out. That is why your jQuery does not work/update.
For example, if you do this:
$('.button').on('click',function(){
var whatever = <?php echo rand() ?>;
alert('This value is'+whatever);
});
It will run the php first so you will end up with the random number off the bat:
$('.button').on('click',function(){
var whatever = 3241231;
alert('This value is'+whatever);
});
No matter how many times you click the button element, it will always say 3241231 until you reload the page when PHP will run the rand() function at load.
To make it load in real time, you need to create an ajax listener to receive a value from the target, send to the backend PHP, then when that backend page responds, you place the response back into your currently loaded page, altering the DOM.
A simple example would be:
/index.php
<?php
# Create the back end to listen for your front end ajax
if(!empty($_POST['test'])) {
# Do your code here to send back.
$rand = rand();
die('Ajax done! Here is a random number: '.$rand);
}
?>
<!-- CLICK ELEMENT -->
<div id="button">CLICK</div>
<!-- PLACEMENT ELEMENT -->
<div id="response"></div>
<script>
$(function(){
// When you click the div
$('#button').on('click',function(){
// Fire the ajax to the same page (you may want to do a
// different page in production). Note, I am referencing a new instance of
// of index.php in the background and sending $_POST['test'] = true as noted
// in the data section of the ajax below.
$.ajax({
'url': '/index.php',
'type': 'post',
// Send the data from the click or whatever
'data': {
'test':true
},
// If there are no server errors,
'success': function(response){
// place the phrase 'Ajax done! Here is a random number: 123124'
// back into the placement div
$('#response').text(response);
}
});
});
});
</script>
In this example, the random number will change each click of the div. Anyway hope this example was helpful.
Having a difficult time trying to suss this out. I've searched through, but I'm not sure if the phrase I'm using to search is correct or not.
I have a JSON file that I'm using to bring in an array of data from an outside source. Using PHP, I decode the contents. I've created a dropdown box that will display the keys, but what I'm looking to do now is dynamically populate a printout with the different values that the keys are attached to based on what the select box has selected.
<?php
// JSON string
$json = file_get_contents("showrace.json");
$races = json_decode($json, true);
?>
<select id="raceSelect">
<option value="select one" selected>Select One</option>
<?php foreach($races as $key => $value) { ?>
<option value="<?php echo $key ?>"><?php echo $value['race'] ?></option>
<?php } ?>
</select>
<div id="template">
Str Plus: # Dex Plus: # Wis Plus: # Int Plus: #<br>
</div>
And here is a sample of what the JSON file looks like:
{
"Ithorian":{"price":0,"wis":3,"str":2,"lck":0,"int":2,"frc":0,"dex":-2,"con":2,"cha":-3,"app":"No","hp":1200,"ac":0,"race":"Ithorian","lang":"ithorian"},
"Weequay":{"price":1000,"wis":-2,"str":3,"lck":0,"int":-2,"frc":0,"dex":0,"con":2,"cha":-3,"app":"No","hp":1350,"ac":0,"race":"Weequay","lang":"weequay"}
}
In the first snippet, the #'s in the template div will be outputs for the JSON values such as "str" and "dex" and such. While I was able to find out how to set the select to draw in the keys from the JSON, I am baffled at how to populate the template portion with the corresponding values, based off of the selected item.
Thanks in advance!
This may help you get started, as it is not fully fleshed out for everything. But it covers some basics you could use.
First off you would want an onchange handler in your jquery. This will fire off everytime someone changes their choice with the :
$("#raceSelect").change(function(e){
// magic will go here (see further below)
});
// or
$("form").on("change","#raceSelect",function(e){
// magic will go here (see further below)
});
Next up you would want to have access to all that json data in your jquery area to use for displaying those values based on what they chose:
<script>
// define this in your php page output near the top
// or within your jquery .ready block
var jsonData = <?PHP echo $json;?>;
</script>
Now you are ready to do some of the magic with the onchange. Accessing the right array in the jsonData, with the id chosen, you can swap out spans and divs to your hearts content. A combined example is as follows:
<?PHP
// your php script
$json = file_get_contents("showrace.json");
$races = json_decode($json, true);
?>
<!-- your form here as you have it in your example -->
<div id="template">
Str Plus: <span id="dat_str">#</span> Dex Plus: # Wis Plus: # Int Plus: #<br>
</div>
<script>
$( document ).ready(function() {
// this is your jquery .ready block
var jsonData = <?PHP echo $json;?>;
$("form").on("change","#raceSelect",function(e){
var race = $(this).val();
$("#dat_str").html( jsonData[race].str );
// you can set the dex, and wiz, etc as well
// following the same format to assign
});
});
</script>
Disclaimer: I hand typed this out, and didn't vett or test it. Its purely an example of pieces that should hopefully help you out.
you can do it using JS
var raceSelect = $('#raceSelect').find(":selected").text();
and check out this link on how te select from json
then print what you want
select from json
Question: I have two drop-down boxes. Using jQuery, I want to populate second drop-down box on selection of the first drop-down box (help with my existing code). I have marked the area I need help with in the jQuery code below, plus an explanation of what I want to achieve in "Code help".
I realise this is a VERY frequently requested item on SO and I have seen many comments that this can be done in simple JS, but since there are already other jQuery elements in use on the page (not coded by me) and for simplicity, I want to use JQ.
I am completely new to any jQuery code, I have researched many examples, however I am getting lost in the logic since I am not familiar with JS or JQ coding conventions, so keeping things simple is important so I can understand what is happening within the code (I am not just looking for help to get my code working, but also so I can learn and understand what is happening).
I found pretty much exactly the operation I want to achieve (except for one important point explained in "Code help" below) by following a tutorial here: http://jqueryfordesigners.com/populate-select-boxes/. A sample page showing the operation is here: http://jqueryfordesigners.com/demo/select-boxes.html
Code help: In the tutorial, the second dropdown is populated from the content of static html files in: $article.load('select-boxes-' + categoryName + '.html');
I need the second dropdown to be populated from the JS variable $st_list and the PHP variable $student_block based on the selected value in the first dropdown, as shown in my code below.
Could anyone please help with how to adapt the code to make that happen?
Thank you
My code:
For simplicity, the first dropdown is static with simple integer values, but will be populated from the DB in $test_seq in the working code with integer values same as the example code below (if that matters). Additionally, in a separate PHP process (later) the $test_seq, $student_id and other new variables will be used to send back data to the DB (included for reference only, though not relevant for this request).
select-boxes.php
$sql = "SELECT * FROM TBL_NAME";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array( $result ))
{
$test_seq = $row['SEQ'];
$student_id = $row['st_num'];
$student_name = $row['st_name'];
$student_block .= '<OPTION value="'.$student_id.'">'.$student_id.' - '.$student_name.'</OPTION>';
}
Form:
<form action="select-boxes.php">
<label for="test_day">Test day:</label>
<select name="test_day" id="test_day">
<option selected value=""> </option>
<option value="1">Day 1</option>
<option value="2">Day 2</option>
<option value="3">Day 3</option>
</select>
<input type="submit" id="next" value="next »" />
</form>
jQuery:
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
$(document).ready(function () {
var $test_day = $('#test_day'),
$st_list = null;
$test_day.change(function () {
var test_dayVal = $test_day.val();
if ($st_list == null) {
$st_list = $('<select name="st_name" id="st_name"><?php echo $student_block; ?></select>').appendTo('form');
$next.remove();
$('form').append('<input type="submit" value="process »" />');
}
$st_list.load('#test_dayVal'); //<--I think this is where I need help.. What do I do here?
});
var $next = $('#next');
$next[0].setAttribute('type', 'button');
});
</script>
I'm designing a registration form in PHP using html. The form collects personal info from users some fields include the marital status, name of spouse, and the number of children. How can I code it such that whenever a user selects "Single" for his/her marital status, the textboxes for the name of spouse and number of children will be automatically disabled? All of this must be done without refreshing the page. Thanks!
Assuming you are using drop down for marital status, use the onchange event to capture the change in the drop down status
function maritalStatusChange()
{
var dropdown = document.getElementById("maritalstatus").value;
if(dropdown == 'Single')
{
document.getElementById("spousefld").readOnly = "readonly";
}
}
You can use JS for your purpose.
Try this code : (Assuming "single" is your radio button)
if (document.geElementById('maritalStatus').checked){
//disable resp textboxes
document.geElementById('spouce').disabled = true;
document.geElementById('children').disabled = true;
}
for more details see this
you can achieve this using the javascript function.
if you have used combobox for marrital status
<select id="a" onchange="if( this.options[this.selectedIndex].value=='s')
{document.getElementById('spouce').readOnly = true;}
">
<option value='s'>single</option>
<option value='m'>married</option>
</select>
<input type='text' id='spouce'/>
see the jsfiddle
I have a list of countries and their area codes in a database. I am trying to auto update a text field with the countries area code when a select option is selected.
ex.
<select name="country">
<option value="CA" code="+1">Canada</option>
...
</select>
<input type="text" name="phone" />
I need to pass on to the script the value CA and the users need to see Canada. Basically what I'm asking is can I create a new option code and have jQuery update the text field that I choose to it.
Is this possible to do? or is there another way I can accomplish this?
Edit: "code" is supposed to be the country's area code. So when a user selects Canada for example the text field phone gets updated with +1. I know I can just set value to +1 and then use .change() to update phone's .val() but I need the current value to pass on to the script that processes it.
I suggest you use an HTML5 data- attribute instead of a custom attribute:
<select name="country">
<option value="CA" data-code="+1">Canada</option>
...
</select>
<input type="text" name="phone" />
and then bind a handler to the change event:
$('select[name="country"]').change(function() {
$('input[name="phone"]').val($(this).children('option:selected').data('code'));
});
or with less jQuery:
$('select[name="country"]').change(function() {
$('input[name="phone"]').val(this.options[this.selectedIndex].getAttribute('data-code'));
});
Another option would be to have a country -> code map in JavaScript
var map = {
'CA': '+1',
...
};
and then look up the code.
Be sure to assign each element an id.
var code = $('#country option:selected').attr('code');
$('#phone').val(code);
If "code" doesn't work. Use "title".
Not entirely sure what you're asking, but dos this help?
$('select[name=country]').change(function() {
$('input[name=phone]').val($(this).find('option:selected').attr('code'));
alert('Do something else with this: ' + $(this).val());
});
$("select[name='country']").change(function() {
$("input[name='phone']").val($(this).find('option:selected'));
});
You can try this. It ties into the select menus change event and then gets the "code" attribute value and sets the text of the input to it.