Setting dropdown values in a table using jQuery

Currently, I am faced with a challenge while trying to assign values to a dropdown list in a table by looping through each row. The issue lies in the incorrect iteration of the table rows using something like $("#myTable tr").each(function(). Any assistance on this matter would be greatly appreciated.

The objective is as follows:

  1. Split string by comma and iterate through table rows
  2. Assign the value to the left of = to the dropdown selection
  3. Assign the value to the right of = to the textbox

Link to My Code Fiddle

HTML:

<table width="100%" class="tblQueryBuilder">
<tbody>
    <tr>
        <th></th>
        <th>Field</th>
        <th>Operator</th>
        <th>Value</th>
        <th></th>
        <th></th>
    </tr>
    <tr class="tr_clone">
        <td><div id="cItem" style="width: 14px; height: 14px; float: left;" class="unchkd"></div></td>
        <td>
            <select style="width: 150px;" class="selField">
                 <option value="Title" selected="selected">Title</option>
                 <option value="ProjectStatus" selected="selected">Project Status</option>
                 <option value="Tags">Tags</option>
            </select>
        </td>
        <td>
            <select style="width: 150px;" class="selOperator">
                <option>=</option>
                <option>&lt;&gt;</option>
                <option>in</option>
            </select>
        </td>
        <td><input type="text" style="width: 150px; height: 25px;" class="selValue"></td>
        <td>X </td>
        <td>= </td>
    </tr>
    <tr class="tr_clone">
        <td><div id="cItem" style="width: 14px; height: 14px; float: left;" class="unchkd"></div></td>
        <td>
            <select style="width: 150px;" class="selField">
                <option value="Title">Title</option>
                <option value="ProjectStatus">Project Status</option>
                <option value="Tags">Tags</option>
            </select>
        </td>
        <td>
            <select style="width: 150px;" class="selOperator">
                <option>=</option>
                <option>&lt;&gt;</option>
                <option>in</option>
            </select>
        </td>
        <td><input type="text" style="width: 150px; height: 25px;" class="selValue"></td>
        <td>X </td>
        <td>= </td>
    </tr>
    <tr class="tr_clone">
        <td><div id="cItem" style="width: 14px; height: 14px; float: left;" class="unchkd"></div></td>
        <td>
            <select style="width: 150px;" class="selField">
                <option value="Title">Title</option>
                <option value="Tags">Tags</option>
                <option value="ProjectStatus">Project Status</option>
            </select>
        </td>
        <td>
            <select style="width: 150px;" class="selOperator">
                <option>=</option>
                <option>&lt;&gt;</option>
                <option>in</option>
            </select>
        </td>
        <td><input type="text" style="width: 150px; height: 25px;" class="selValue"></td>
        <td>X </td>
        <td>= </td>
    </tr>
</tbody>
</table>

Javascript

var qry = 'Title=new project,Project Status=0,Tags=a';
        var qryRowCount = qry.split(',').length;

for (i = 0; i < qryRowCount; i++) {
    var fieldVal = qry.split(',')[i].split('=')[0];
    var displayVal = qry.split(',')[i].split('=')[0];

    $('.selField').val(fieldVal);
    $('.selValue').val(displayVal);
}

Answer №1

By assigning the tags f1 to f3 for each dropdown list and its corresponding textfield, and d1 to d3, they can be uniquely identified when looping through table rows.

JS CODE:

  var qry = 'Title=new project,ProjectStatus=0,Tags=a';
  var qryStr = qry.split(',');
  var qryRowCount = qryStr.length;

for (i = 0; i < qryRowCount; i++) {
   var fieldVal = qryStr[i].split('=')[0];
   var displayVal = qryStr[i].split('=')[1];
   var fieldId = "#f" + (i + 1);
   var displayId = "#d" + (i + 1);
   $(fieldId).val(fieldVal);
   $(displayId).val(displayVal);
}

JSFIDDLE: http://jsfiddle.net/232HA/19/

I have made some adjustments to your code, hoping it resolves your issue.

Happy Coding :)

Answer №2

<button type="button" onclick="updateSelections()">Select Items</button>
<script>
function updateSelections(){
    $(".tblSelector tr").each(function(index, elem) {
        if (index == 0) return;

        var selection = $("input", this.cells[4]).val();
        var selectionCount = selection.split(',').length;

        for (i = 0; i < selectionCount; i++) {

            var item = selection.split(',')[i].split('=')[0];
            var label = selection.split(',')[i].split('=')[1];

            $('.selectedItems', this).append("<option value=" + item + ">" + label + "</option>");
        }
    });
}
</script>

Integrating this snippet into your code will enhance the select functionality. Is this what you were looking for?

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

Converting a PHP timestamp to a jQuery-compatible format

Can someone help me find the equivalent function in jQuery that will give me a time format similar to this: date( 'Y-m-d\TH:i:sP'); //the output is like this. 2013-10-30T18:10:28+01:00 I am looking for this specific format in jQuery to use ...

"Utilize the power of the ajaxform jQuery plugin to automatically reset form fields

Initially, I'd like to emphasize that this is an original inquiry. My predicament is as follows: I have a chatroom php script where I utilize the ajaxForm jQuery plugin to seamlessly send new messages without having to reload the entire page. Howev ...

Encasing common functions within (function($){ }(jQuery) can help to modularize and prevent

As I was creating a global JavaScript function and made some errors along the way, I finally got it to work after doing some research. However, while searching, I came across an example using (function($){ code here }(jQuery); My question is, what exact ...

Obtaining the responseJSON property from a jQuery $.ajax object involves accessing the data returned

Recently, I encountered an issue with my JavaScript code that involves an AJAX request: $ajax = $.ajax({ type: 'GET', url: 'DBConnect.php', data: '', dataType: 'json', success: function(data) {} ...

Verifying if a number is present in a textbox when inserting text (without using setTimeout)

I have an input field similar to the one shown below: <input type ="number" id="numberTxt" placeholder="Number Only"/> To ensure that the value entered is a number, I am using the following function with the keypress event: <script> ...

Ajax is coming back with a value that is not defined

Currently, I am working on a search function that is responsible for searching a name from the database. When the user clicks "add", the selected item should appear below the search field so that it can be saved in the database. However, I am encountering ...

Using special characters as parameters in Ajax requests

I need assistance with sending data via Ajax to my controller action. Here is the code snippet: $.ajax({ url: "/cotroller/action", data: { fieldsOfStudy: $('[name=fieldsOfStudy]').serialize()} }) The 'fieldsOfStudy' select bo ...

Choose the specific Element by its dynamicID in JQuery

Just starting out with Jquery and I have a specific task in mind. In my HTML page, I have elements with IDs generated by concatenating a string variable. My goal is to use JQuery to select the element with this dynamically generated ID. See below for more ...

Animating the left and right positioning of a single element using CSS transitions

I am currently working with the following CSS code: #masthead { transition: left linear 0.25s; -moz-transition: left linear 0.25s; -o-transition: left linear 0.25s; -webkit-transition: left linear 0.25s; -ms-transition: left linear 0.2 ...

Getting the location of a mouse click and adding tags (marks) on an image: a simple guide

Is there a way to incorporate images with tagged marks similar to Facebook's image tagging feature? How can I retrieve the X and Y coordinates of tags on the image itself (not the screen) and display them in a responsive manner? ...

Passing a missing parameter to ASP MVC controller via jQuery/Ajax

Currently, the operation that should be simple is not working as expected in my program. The user should be able to input text into a field on the view and then click on the magnifying glass icon. This action would send the text to the controller, which wo ...

Click on the jq toggle button to increase productivity and complete additional tasks

Is it possible to use a toggle function to create a drop-down menu while also rotating the mobile menu icon image when clicked? Can this be accomplished within the same function, or would I need to add a new event listener to the image? jQuery('#mobi ...

Utilizing long polling technique with jQuery/AJAX on the server end

Currently, I am facing an issue with long polling on a single page that contains multiple pages. The problem arises when a new request is made while a previous request is still processing. Even though I attempt to abort the previous request, it completes b ...

.encounter issue with loading Internet Explorer

Currently, I am utilizing the .load method to load some data into a div. It is functioning properly overall, but when attempting to specify and load a particular ID from the HTML, Internet Explorer fails to load anything. For example: $('div.myDiv&a ...

Creating a Dynamic Dependent Dropdown with Jquery and Ajax in PHP

As a newbie in coding, I stumbled upon some valuable information to enhance my register form using Ajax. While the PHP files seem to be functioning correctly, I suspect that the JS file is not performing as expected. In the register form, you'll find ...

jQuery Mobile and Phonegap: Content Disappears from Page Header After Transition Finish

My phonegap (2.2.0) + jquery mobile (1.2.0) app is experiencing a peculiar problem. There is a page in my app with a link that loads another page. On the loaded page, there is a back button that takes the user back to the previous page when clicked. This ...

Switch between the table data elements in an .hta document

The response provided by Dr.Molle in a previous post here was accurate, but it only functioned with <div>. I am required to utilize <table>. Though I found a script that works flawlessly outside of my VBScript, it does not work when embedded in ...

Is there a way to retrieve a specific section of a webpage using an AJAX GET request?

When making a GET request to the server, we can retrieve an entire page. However, what if I only need the content of a specific div on that page? Do I have to fetch the entire page and then use jQuery's find() method to extract the div content? Or is ...

Generate dynamic lines with evolving hues using CSS3

While working on a fresh web project, I came across the need to emphasize my headers (h1, h2, h3, h4) with underlines. My goal is to have these underlines grow and change color dynamically, similar to what can be seen here: . Is there a way to achieve thi ...

Send a string to the controller through an AJAX request

Seeking assistance on creating a search field to find users within my system. The idea is to input the user's name into the field, then use an Ajax function to pass that name from the search field to a method in the controller. This method will return ...