Troubleshooting a problem with writing to a jQuery form field

Trying to update a hidden field in a form using jQuery. The issue is that it works fine for the first three clicks, but then it only shows the value of the first element.

Check out the working example on jsFiddle here:

When a user clicks on a tab, the value of "fileorurl" changes to 1, 2, or 3. It seems to be working for the first 3-5 clicks, but then it gets stuck at 1. Here is the HTML:

<div class="container" id="upload">
    <div class="row">
        <form id="upload-form2"
              action="http://way2enjoy.com/modules/compress-png/converturl16.php"
              name="arjun"
              method="post"
              enctype="multipart/form-data">
            <div id="tab" class="btn-group" data-toggle="buttons">
                <a href="#fileuu" class="btn btn-default active" data-toggle="tab">
                    <input type="radio" class="changev" value="1">File Upload
                </a>
                <a href="#urluu" class="btn btn-default" data-toggle="tab">
                    <input type="radio" class="changev" value="2">URL upload
                </a>
                <a href="#linkuu" class="btn btn-default" data-toggle="tab">
                    <input type="radio" class="changev" value="3">Website Link
                </a>
            </div>
            <div class="tab-content">
                <div class="tab-pane active" id="fileuu">
                    <label for="comment">Click below to choose files:</label>
                    <input type="file" name="file[]" multiple id="input" class="file_input">
                </div>
                <div class="tab-pane" id="urluu">
                    <label for="comment">Image Urls to Compress:</label>
                    <textarea class="form-control" rows="2" name="urls" id="urls"></textarea>
                </div>
                <div class="tab-pane" id="linkuu">
                    <label for="comment">Website URL to Analyze:</label>
                    <textarea class="form-control" rows="2" name="file[]" id="urls"></textarea>
                </div>
            </div>
            <div class="alert alert-warning" role="alert" id="loading_progress"></div>
            <br>
            <input type="submit"
                   value="Compress »"
                   class="btn btn-primary btn-lg pull-right"
                   id="upload_btn"
                   name="upload_btn">
            <input type="hidden" name="fileorurl" id="myField" value="">
        </form>
    </div>
</div>

And here is the JavaScript code:

<script>
    $('.changev').change(function () {
        var valueuu = $(this).val();
        $("#myField").val(valueuu);
    });
</script>

Any help would be greatly appreciated. Thank you!

Answer №1

It seems like your checkboxes are not updating properly after a few clicks, which is quite strange. One solution could be to use the click event on their parent elements instead:

$('#tab a').on('click', function(){
    var valueuu = $(this).find('input').val(); 
    $("#myField").val(valueuu);
});

Check out this Fiddle for reference.

Answer №2

To achieve this, I recommend using a custom attribute and listening to Bootstrap events. The input's default value is set to 1, indicating the first active tab.

$(document).on('shown.bs.tab', '#tab > a', function(e) {
  var dataType = $(e.target).attr('data-type');
  $("#myField").val(dataType);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container" id="upload">
  <div class="row">
    <form id="upload-form2" action="http://way2enjoy.com/modules/compress-png/converturl16.php" name="arjun" method="post" enctype="multipart/form-data">
      <div id="tab" class="btn-group" data-toggle="buttons">
        <a href="#fileuu" class="btn btn-default" data-toggle="tab" data-type="1">File Upload</a>
        <a href="#urluu" class="btn btn-default" data-toggle="tab" data-type="2">URL upload</a>
        <a href="#linkuu" class="btn btn-default" data-toggle="tab" data-type="3">Website Link</a>
      </div>
      <div class="tab-content">
        <div class="tab-pane active" id="fileuu">
          <label for="comment">Click below to choose files:</label>
          <input type="file" name="file[]" multiple id="input" class="file_input">
        </div>
        <div class="tab-pane" id="urluu">
          <label for="comment">Image Urls to Compress:</label>
          <textarea class="form-control" rows="2" name="urls" id="urls"></textarea>
        </div>
        <div class="tab-pane" id="linkuu">
          <label for="comment">Website URL to Analyze:</label>
          <textarea class="form-control" rows="2" name="file[]" id="urls"></textarea>
        </div>
      </div>
      <div class="alert alert-warning" role="alert" id="loading_progress"></div>
      <br>
      <input type="submit" value="Compress »" class="btn btn-primary btn-lg pull-right" id="upload_btn" name="upload_btn">
      <input type="text" name="fileorurl" id="myField" value="1">
    </form>
  </div>
</div>

Fiddle here: https://jsfiddle.net/zyynnzm9/3/

Answer №3

A re-discovery! Your radio buttons are being checked, but they lack the ability to be unchecked as they are not grouped together... Each one stands alone without connections.

To remedy this, consider placing them in a radio group by assigning the same value to the name attribute for each button.

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

Use jQuery to generate and add several elements to the DOM

Hey there! Currently, I'm working on a real-time chat application using socket io. My goal is to display the user's username and message in a unique way by encapsulating the username in a strong tag. I've made some attempts: $('<div ...

Tally each div individually and display the count within each div, instead of showing the total count across

I have come across various solutions that show the total number of certain special divs, such as: $('.someclass').length However, I am facing a different challenge. I want to sequentially count each div with a numerical sequence. For instance, ...

The Tiny Scrollbar jQuery plugin experiences a malfunction when the defer attribute is added to the script tags in the javascript code

After successfully setting up the jQuery plugin, Tiny Scrollbar, I encountered an issue when I attempted to defer the loading of the necessary javascript files. Here is an example of the code snippet: <script type="text/javascript" src="https://ajax.g ...

What causes a functional component's nested function to access an outdated state value?

My component implements infinite scrolling to fetch and display posts using an IntersectionObserver. The API call made by the component depends on the current number of fetched posts, which is passed as an offset to the API call. The objective is to displ ...

How can I retrieve an Angular application's $templateCache from the global scope?

Looking for a way to efficiently share cached template strings across different JavaScript libraries? I need to utilize $templateCache.get("TEMPLATE.HTML") within an Angular app that is accessible in the public JavaScript scope. If anyone has any suggesti ...

Div element with fixed position that dynamically adjusts its height according to the position of the

Currently, I am designing a website with two sidebars and a center wrapper for the main content. The sidebars will contain links that jump the user to different sections of the page. I have fixed the position of the sidebars so they stay visible as the use ...

What is the best way to send data through a modal using bootstrap?

Today, I am attempting to finish the project, only to realize that the edit function I coded is not functioning correctly. Every time I click on the edit button, it shows the same values instead of displaying the corresponding data in a specific modal. Th ...

What is the jQuery equivalent for converting this JavaScript code?

Here's a code snippet that I am struggling with: data=>{document.querySelector( "#os11.html-widget.gauge svg text[font-size='10px'] tspan" ).innerHTML = data.text I attempted the following solution: $("#os11.html ...

Validating file uploads using JQuery

I have been struggling to transfer a file from ajax to php for some time with no luck. That's why I decided to use JQuery Validate Within my form, there are multiple inputs such as name and email, along with one input of type file. I am able to valid ...

Encountering an Error in Node.js When Defining Routes Using Variable Routes

Here is the code snippet from my App.js file- var routes = require('./routes'); app.get('/', routes.index); //var abt = require('./routes/about'); app.get('/about', routes.about); This is the code from my index.j ...

Ways to verify whether a callback function supplied as a parameter in Javascript has any arguments

My task involves implementing the following: doSomething .then(success) .catch(failure); The success and failure functions are callbacks that will receive their value at runtime (I am developing a module). Therefore, I need to ensure that the fa ...

Keep only certain fields and eliminate the rest

Write a function that filters out all fields except 'firstName' and 'lastName' from the objects. Check out this code snippet I came up with. Any feedback? let people = [ { firstName: 'John', lastName: &apo ...

Extracting data from a designated cell in an HTML table using JavaScript

My table in AngularJS looks something like this: <tr id="table"> <td style="text-align: center">{{flight.FlightFrom}}</td> <td style="text-align: center">{{flight.FlightTo}}</td> <td style="text-align: center"& ...

Alter the color of textbox text using JavaScript

I have a text input field. When clicked, I want to change the text color style using JavaScript. Previously, I successfully achieved clearing the inner content of the textbox when clicked and reverting to the default version on blur. This code is currently ...

Submitting Form data to MySQL database with Node.js using Express framework

Currently, I'm working on a server.js file in Node that is intended to send form data from an HTML file to MySQL. However, I seem to be encountering a syntax error with my code. Below, you'll find the code snippet along with the specific error me ...

What is the best way to clear the field?

This is the code I am currently using to submit a form: <script type="text/javascript"> var frm = $('#blogform'); frm.submit(function (ev) { $.ajax({ type: frm.attr('method'), url: frm.attr ...

Modify the name of the output for form-variables in Django

Currently, I am exploring a Django tutorial for building a "recipe" home-page. As someone who is completely new to Django and html, I find the process quite challenging. In my attempt to create a new class instance using the CreateView, I have defined the ...

Designing draggable tags similar to those on LinkedIn, incorporating a parent div element containing an SVG image and text

Lately, I've been exploring the world of CSS and Angular. Can someone give me a jumpstart on using CSS to design an element like the one shown in this https://i.stack.imgur.com/vcR3Z.png image? Essentially, this outer tag consists of a div element th ...

Encapsulate every list item with a <ul> tag using jQuery

Not going into specifics, I've written some jQuery code like this: $("nav ul ul").each(function () { var navitems = $(this).html(); alert(navitems); }); I understand that .html uses InnerHTML so the alerts display as follows: <li>xxxx ...

The invocation of res.json() results in the generation of CastError

An issue occurs with CastError when using res.json() with an argument: CastError: Failed to cast value "undefined" to ObjectId for the "_id" field in the "Post" model Interestingly, using just res.status(), res.sendStatus(), or res.json() without argument ...