Once a Javascript variable is declared for the first time, it cannot be overwritten

I am currently facing an issue with a function that should refresh the page based on the selected number:

prodName="doesn't matter, not directly $.ajax related"

function searchProduct() {
  var prodName = $("#admin-search-product").val().trim();
  var pagenumb = 1;
  $(".page-item").click(function() {
    pagenumb = $(this).children('.page-link').attr('value');
  });
  alert(pagenumb);
  if (prodName == "") {
    $.ajax({
      type: "POST",
      url: "admin_search_product.php",
      data: {
        search_prod: 0,
      },
      success: function(respond) {
        $("#admin_content").html(respond).show();
        $("#admin-search-product").focus().val('').val(prodName);
      }
    });
  } else {
    $.ajax({
      type: "POST",
      url: "admin_search_product.php",
      data: {
        search_prod: 1,
        searchName: prodName,
        pagenumb: pagenumb
      },
      success: function(respond) {
        $("#admin_content").html(respond).show();
        $("#admin-search-product").focus().val('').val(prodName);
      }
    });
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="admin-search-product">

<div class="page-item">
<input class="page-link">
</div>

<button onclick="searchProduct()">clickme</button>

While everything seems to be working correctly, the issue arises when the variable "pagenumb" retains the value of "1" even after attempting to retrieve the clicked page value using "pagenumb = $(this).children('.page-link').attr('value');". The alert() function confirms that the correct value is being retrieved within the click function.

Strangely, when testing the alert() function outside the click function, it appears that the variable "pagenumb" remains unchanged. This behavior is puzzling as I can successfully retrieve the desired value but encountered difficulty in updating the variable accordingly.

Answer №1

Make sure to attach the event handler once during the initialization of the page, instead of triggering it every time you call searchProducts().
For updating the value of pagenumb, use the change event, not click. Clicking will only attempt to update the value when the input box is focused, which may not be the desired behavior.

prodName = "not relevant for $.ajax"

var pagenumb = 1;

// Attach this event handler _once_ on page load
// Use the change event, not click. Update pagenumb whenever value changes
$(".page-item").change(function() {
  // Convert to a number using the + operator
  pagenumb = +$(this).children('.page-link').val();
});

function searchProduct() {
  var prodName = $("#admin-search-product").val().trim();

  alert(pagenumb);
  if (prodName == "") {
    $.ajax({
      type: "POST",
      url: "admin_search_product.php",
      data: {
        search_prod: 0,
      },
      success: function(respond) {
        $("#admin_content").html(respond).show();
        $("#admin-search-product").focus().val('').val(prodName);
      }
    });
  } else {
    $.ajax({
      type: "POST",
      url: "admin_search_product.php",
      data: {
        search_prod: 1,
        searchName: prodName,
        pagenumb: pagenumb
      },
      success: function(respond) {
        $("#admin_content").html(respond).show();
        $("#admin-search-product").focus().val('').val(prodName);
      }
    });
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="admin-search-product">

<div class="page-item">
  <input class="page-link">
</div>

<button onclick="searchProduct()">clickme</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

The search functionality in an Html table is currently malfunctioning

Currently, I am working on developing a search mechanism in HTML. It seems to be functioning properly when searching for data for the first time. However, subsequent searches do not yield the expected results. Additionally, when trying to search with empty ...

The component 'createSvgIcon' from 'material-ui' is not available in the 'utils' module of '@material-ui/core'

After installing material-ui/lab to utilize the alert component, I encountered an issue when trying to import it using import Alert from '@material-ui/lab/Alert';. It failed to compile and threw the following error: ./node_modules/@material-ui/l ...

Am I making a mistake in my implementation of sending Socket.io messages to a designated room?

Upon a user joining, I alter their ID to a shortened random code. This change is made to utilize the id as a visible session ID on the front-end. I mention this to prevent confusion regarding non-standard socket IDs and their relation to potential issues. ...

Enable arrow keys feature in Regular Expressions

Currently, I am implementing alphanumeric validation to ensure that users can only input alphanumeric values and also paste alphanumeric values exclusively. In order to achieve this, I have utilized the following regular expression: function OnlyAlphaNum ...

Holding off on triggering a jQuery Ajax request until a function returns a value

I'm currently facing an issue where an Ajax request is not waiting for a function call to return before executing. The specific scenario involves calling getSelectedMessages to retrieve checkbox values and then passing these values in an array to the ...

How can I prevent JQWicket's AjaxSlider from sliding to the right?

As a beginner in RIA-development, I am currently exploring the JQWicket's Ajax Slider Example. My goal is to create a page with two Ajax sliders and a counter. The main objective is for the user to adjust the slider values based on the counter, witho ...

Integrate my API with HTML using J.Query/Ajax technology

Finally, after much effort, I have successfully created a JSON java API. My API design is simple and based on Interstellar movie details: { "title": "Interstellar", "release": "2014-11-05", "vote": 8, "overview": "Interstellar chronicl ...

When using setInterval in a React app with TypeScript, incorporating dependencies from the state can result in the interval stopping prematurely

One aspect that I find challenging in a React application is properly utilizing setInterval when needing an option to exist early while keeping the interval running. This particular option is a piece of state within the app. The useEffect block below illu ...

bespoke filter designed to conceal any negative figures

I am trying to implement a feature where a text box will display nothing if the ng-model contains a negative value. I want the ng-model to remain unchanged while ensuring that negative values are not displayed. I am looking for a custom filter to achieve t ...

Using HTML5 Canvas with Firefox 4: How to Retrieve Click Coordinates

Lately, I've been diving into creating HTML5 Video and Canvas demos. Initially, my focus was on optimizing them for Chrome, but now I'm shifting my attention to Firefox and Safari as well. One particular demo I'm currently working on involv ...

Best practices for incorporating and leveraging node packages with Laravel Mix

As I embark on my Laravel (v 8.x) Mix project, I am encountering challenges when it comes to incorporating JavaScript from node modules. To kick things off, here is a snippet from my webpack.mix.js: mix.js('node_modules/mxgraph/javascript/mxClient.mi ...

Encountered a Server Error: Invalid hook call. Hooks are restricted to being called within the body of a function component specifically in _app.js

As someone new to React and Next JS, I am facing an issue with setting initial auth user data on the initial load from the __app.js file. Whenever I try to use dispatch, it throws an error saying "Invalid hook call". I understand that calling hooks in the ...

What is the best way to show information entered into a textbox on a different webpage?

Looking for advice on how to collect data in a text box and display it on another page? I have included HTML code for both the announcement page (where the data is entered) and the archive page (where the data should be shown). Could someone guide me on ...

Firefox Exclusive: NS_BINDING_ABORTED Error when Opening Bootstrap Modal

Encountering a dilemma here, I have combined bootstrap modal with FullCalendar.io to input appointments into an app. Everything functions flawlessly on Google Chrome; however, in Firefox, the ajax request to add the appointment seems to have no effect. The ...

Display the array of selected values on the console upon clicking the submit button

After creating a function that saves checked values in the 'Arr' array, I am facing an issue where the array is being printed multiple times when the "View Results" button is clicked. This results in the checked values appearing multiple times on ...

Where does the browser retrieve the source files for "sourcemapped" JavaScript files from?

As I begin working on an existing project built with angular JS, upon opening chrome dev tools and navigating to the "source" view, a message appears: Source map detected... This prompts me to see a link to: https://i.stack.imgur.com/RZKcq.png The fi ...

Upgrade the WordPress light editor to the advanced version

After developing a script to upgrade the WordPress editor on a specific page from light mode to Advanced once a user clicks the Unlock button and confirms their desire to make the switch, an issue arose. Despite deducting 5 coins from the user's balan ...

Why isn't Jquery validate working for the day input?

I am facing an issue with a script that triggers only when I click on a textbox for the first time: var day = parseInt($("#day_birthdate").val(), 10); jQuery('input#day_birthdate').bind('input propertychange', function () { ...

In the strict mode tree, a reference named "grid" has been discovered

I encountered the following warning in the console: Warning: A string ref, "grid", has been found within a strict mode tree. String refs can potentially lead to bugs and should be avoided. It is recommended to use useRef() or createRef() instead. T ...

The location layer on my Google Maps is not appearing

For a school project, I am working on developing a mobile-first website prototype that includes Google Maps integration. I have successfully added a ground overlay using this image, but I am facing issues with enabling the "my location layer". When I tried ...