I keep receiving a JavaScript alert message saying "undefined."

When I try to alert the item_id after giving input in the quantity textbox, I am receiving an undefined JavaScript alert. The code snippet below is not displaying the alert as expected:

var item_id=$("#item_"+i).val();alert(item_id);

In addition, my model and controller are not displaying the item properly. Can someone please assist me with this issue?

This is how my view looks like:

<td style='width:20%' id='producttd_1'>
  <select name='item[]' id='item_1' class="form-control selectpicker"  style='width:100%'  data-show-subtext="true" data-live-search="true" >
    <?php
    if(!empty($prolist))
    {
    print_r($prolist);
        foreach($prolist as $pro)
        {
            $opn1.="<option value='".$pro['id']."'>".$pro['product_name']."</option>";
        }
    }
    ?>
  </select>
</td>
<td style='width:7%'><input type='text' name='nos[]' id='nos_1' class="form-control" style='width:100%'/></td>
<td style='width:7%'><input type='text' name='quantity[]' id='quantity_1' class="form-control addrow quantity"  style='width:100%' onKeyup='calc(1);'/></td>
<td style='width:7%'><input type='text' name='rate[]' id='rate_1' class="form-control addrow" style='width:100%' onKeyup='calc(1);'/></td>

Below is the relevant AJAX code:

function calc(i)
{
    if(event.keyCode == 13) {
        add_row();
    }
    else
    {
        var item_id=$("#item_"+i).val();
        alert(item_id);
        var rate=$("#rate_"+i).val();

        // Other code logic goes here...
    }
}

And here's my controller snippet:

function product_det()
    {
        $item=$this->input->post('item_id');
        echo $item;

        // More code for processing product details...
    }

Finally, this is my model function for fetching product details:

function get_productDet($item)
{
     $this->db->select('*');
     $this->db->from('product');
     $this->db->where('id',$item);
     $res=$this->db->get()->row_array();
     return $res;
}

Answer №1

Retrieve the value of the option that is currently selected, not the select element itself:

var selectedOptionValue = $("#item_1").find(":selected").text();
alert(selectedOptionValue);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JSON has difficulty retaining the value of the variable

I've been working on a piece of code that scans through a directory, extracts each file's name and content. The aim is to retrieve the data from these files, usually consisting of numbers or short pieces of text. var config = {}; config.liveProc ...

JavaScript | Calculating total and separate scores by moving one div onto another div

I have a fun project in progress involving HTML and Javascript. It's a virtual zoo where you can drag and drop different animals into their designated cages. As you move the animals, the total count of animals in the zoo updates automatically with the ...

What is the best way to specify a type for an object without altering its underlying implicit type?

Suppose we have a scenario where an interface/type is defined as follows: interface ITest { abc: string[] } and then it is assigned to an object like this: const obj: ITest = { abc: ["x", "y", "z"] } We then attempt to create a type based on the valu ...

Guide to retrieving a specific cookie value with socket.io

I have successfully retrieved all cookies using the socket.request.headers.cookie. Upon console logging, the output appears as follows: PHPSESSID=mtklg8k81cpkop5ug6aechbb34; user=77; io=1Klg6xgTRXhb2OWiAAAA Now, I am trying to extract only the value of ...

What are the security risks of evaluating user-supplied strings in web browser storage?

I'm in the final stages of developing a script that creates an API for performing storage operations across various web browser storage technologies. Currently, I am focusing on adding conditional retrieval and removal functionalities. These features ...

Using Typescript to remove an element from an array inside another array

I've encountered an issue while trying to remove a specific item from a nested array of items within another array. Below is the code snippet: removeFromOldFeatureGroup() { for( let i= this.featureGroups.length-1; i>=0; i--) { if( this.featureGr ...

JavaScript breaks when using jQuery Ajax to pass an email to a PHP script

Whenever I try to pass variables to my mail.php script for email composing, the script breaks down as soon as I enter an email address. It seems like the email is automatically converted to a URL, causing my JavaScript to crash. Am I misunderstanding some ...

delay in displaying options when toggling visibility in a dropdown menu

When you first click on the select, it displays incorrectly https://i.sstatic.net/Ax9T7j8J.png But when you click on it a second time, it displays correctly https://i.sstatic.net/UpW4krED.png $(document).on("click", "#edit_afpDetalle_mes&q ...

Can I use Javascript to make changes to data stored in my SQL database?

I am delving into the realm of SQL and Javascript, aiming to insert my variable ("Val_Points from javascript") into a table ("Usuarios") associated with a specific user (e.g., Robert). Is it possible to achieve this using JavaScript, or are there alternati ...

Issue with Jest mock function failing to trigger axios instance function causing it to return undefined

I initially found a solution on this StackOverflow thread However, I wanted to add my own helper function that generates a fresh Axios instance with the user's authentication token. Here is what I came up with: import axios from "axios"; c ...

Refreshing a form following an ajax call using the ajaxForm method

I have implemented the following code to submit my form using ajaxForm plugin: $('#donations').ajaxForm({ dataType: 'json', beforeSubmit: function(){ $('#message').html(''); ...

Having trouble with Angular router.navigate not functioning properly with route guard while already being on a component?

I am currently troubleshooting an issue with the router.navigate(['']) code that is not redirecting the user to the login component as expected. Instead of navigating to the login component, I find myself stuck on the home component. Upon adding ...

What are the consequences of excluding a callback in ReactJs that may lead to dysfunctionality?

<button onClick = { () => this.restart()}>Restart</button> While going through a ReactJs tutorial, I encountered a game page which featured a restart button with the code snippet mentioned above. However, when I tried to replace it with the ...

Exploring the attributes of cycled values in Vue.js

Currently, I am iterating over a list as shown below: <li v-for="item in filteredParentItems" v-if="item.action === 'list'" v-on:click="getNextPath" v-bind:data-next-path="item.nextPath" v-bind:data-action="item.action ...

Is it possible to use ajax to upload files, as demonstrated below?

Is it possible to upload a file using AJAX? Currently, I am only able to retrieve the file name. $(document).ready(function() { $("#uploadbutton").click(function() { var filename = $("#file").val(); $.ajax({ type: "POS ...

"Using a triangular background shape in JavaScript instead of a traditional circular

I want to add a unique effect to my site inspired by the AnimatedHeaderBackgrounds demo available at this link. My twist on this effect involves using upward-moving triangles instead of circles. I've explored various resources, including Stack Overfl ...

Encountered an error while trying to find the Node JavaScript view

Whenever I attempt to render the URL for displaying index.js in the browser, an error arises: **Error:** Failed to locate view "index" in views directory "D:\NodeJs\Example\5expressnodjsexmp\views" Below is my application code: //Hea ...

Error: The object does not have the property createContext necessary to call React.createContext

I'm currently exploring the new React Context API in my app. I've also implemented flow for type checking. However, when I add // @flow to a file that contains the code: const MyContext = React.createContext() An error pops up stating: Cannot ...

Trouble encountered when integrating npm library with webpack

Recently, I set up a webpack project with vuejs using the template from https://github.com/vuejs-templates/webpack-simple. My intention was to integrate https://www.npmjs.com/package/bravia into my vue application by importing it with import Bravia from &a ...

Changing the value in sessionStorage does not trigger the onChange event (Next.js)

When I use a custom hook to load data from session storage into an input field, I noticed that the onChange() function doesn't trigger if I delete the entire content of the input. However, it works fine if I add or delete just one character. This issu ...