Perform the action when the button is clicked

I'm struggling with finding a solution to this problem. I have an input field and a submit button. My goal is to update the value of a variable to match the value in the input field when the submit button is clicked.

Additionally, I need to execute a function when the submit button is clicked. Specifically, when the button is clicked, I want to retrieve a JSON file from Wikipedia based on the input given in the text field.

    <div class="container">
    <div class="row">
        <div class="span8"><p>Please enter your search term:</p>
        <input id="input" type="text"  value="Denmark"><br>
            <input type="button" id="submit" value="Search" />
        </div>
        <div class="span4"><div id="result"></div></div>
    </div>
 </div>


<script>
var searchTerm="";
var url="http://en.wikipedia.org/w/api.php?action=parse&format=json&page=" + searchTerm+"&redirects&prop=text&callback=?";

$('#submit').click(function (){
searchTerm='denmark';
});


$.getJSON(url,function fetchWiki(data){
  wikiHTML = data.parse.text["*"];
  $wikiDOM = $("<document>"+wikiHTML+"</document>");
  $("#result").append($wikiDOM.find('.infobox').html());
});

I'm having trouble implementing the changes required for updating the value and running the function accordingly.

Your patience is appreciated as I am still learning JavaScript.

Answer №1

To prevent the default action of the click event, make sure to add this code snippet:

$('#submit').click(function (e){ //pass the event into the function
 e.preventDefault(); //stop the submit button from submitting

 //update variables accordingly
 searchTerm = $("#input").val();
 url="http://en.wikipedia.org/w/api.php?action=parse&format=json&page=" + searchTerm+"&redirects&prop=text&callback=?";

 $.getJSON(url,function fetchWiki(data){
   wikiHTML = data.parse.text["*"];
   $wikiDOM = $("<document>"+wikiHTML+"</document>");
   $("#result").append($wikiDOM.find('.infobox').html());
 });

});

Remember to place the search code inside the click function so that variables are updated after clicking "submit".

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

Tips for crafting interactive Dropdown menus

Visit this link for more information Hello all, I am a beginner in HTML and Javascript and seeking guidance on how to create dynamic dropdown menus similar to the ones on the provided website. I have successfully implemented the source code, but my questi ...

Searching for a specific text within an element using XPATH in C# with the Selenium framework

My current challenge involves locating specific text within certain elements on an HTML page. <a class="ProductCard-link ProductCard-content" target="_self" tabindex="0" href="/en/product/puma-future-rider-menshoes/314 ...

Revise the JSON data by incorporating user-provided input and transforming it into XML

I need to take CSV data, display it to the user with input fields, and then update Json before converting everything to XML. Can I update Json using user inputs, or is there a different approach? $(document).ready(function() { $.getJSON( &apos ...

Customize and format the text of options in a select element using the jQuery Chosen plugin

I have been exploring the jQuery plugin chosen for a select box with autocomplete functionality. You can check it out here: Does anyone know how to customize the appearance of the text in the options of the select box? Is there a specific method within t ...

Transmitting a plethora of information using jQuery

Here's the code I currently have for sending data: var test={imagename:"apple.jpg",x:"13",y:"33"}; $.ajax({ type: "POST", url: "some.php", data: test, success: function(response){ console.log(response); } }); ...

Only the initial AJAX request is successful, while subsequent requests fail to execute

I am facing an issue with multiple inputs, each requiring a separate AJAX request. < script type = "text/javascript" > $(document).ready(function() { $("#id_1").change(function() { var rating1 = $(this).v ...

Fixing the issue of 'Unrecognized character < in JSON at position 0 at JSON.parse'

I have recently deployed my Angular 6 application on Heroku at . However, upon deploying, I encountered the error message: SyntaxError: Unexpected token < in JSON at position 0 during JSON.parse. I am aware that this error occurs when the response ret ...

HTML template without the use of server-side scripting languages like PHP or Ruby on

Is there a way to develop HTML templates without relying on backend languages such as PHP or Ruby on Rails? I tried using JavaScript, but I encountered issues with my current code when adding nodes after the DOM is loaded. An ideal solution for me would ...

Can you specify the doctype used for XHTML5, which is the XML representation of HTML5?

Which doctype is recommended for XML serialization of HTML5? If I keep the file extension as .html, can I still indicate to the browser that the content is XHTML5? ...

Automatically selecting the country phone code based on the country dropdown selection

When the country dropdown is changed, I want the corresponding phone code dropdown to be dynamically loaded. <div class="row"> <div class="col-sm-8 col-md-7 col-lg-6 col-xl-5 pr-0"> <div class="form-group py-2"> <l ...

Attempting to place the search bar within the navigation bar

Having trouble positioning a search bar in my nav bar, I'd like it to show on the right side without overlapping any other elements. Tried relative and absolute positioning with no success so far. Any assistance would be greatly appreciated, thank yo ...

Exploring the functionality of the 'useBodyParser' option in Nestjs

Issue with 'useBodyParser' in Nestjs Application I am encountering an error when trying to utilize the useBodyParser option on my Nestjs application instance. Error: Property 'useBodyParser' is not found on type 'NestExpressAppl ...

Using JavaScript, aim for a specific element by its anchor headline

I'm looking to make some changes to my navigation menu, specifically hiding the home menu item unless the mobile navigation menu is toggled. Is there a way for me to target the "home" anchor title and apply the active class to it when toggled, similar ...

What is the best way to align this alert in the center of the screen

Hey there, I'm facing an issue with aligning an alert horizontally when a user clicks a button. I've been trying different methods but can't seem to get it right. The goal is to keep the alert within #main. You can check out this fiddle for ...

Creating responsive images using Bootstrap CSS framework

I have been focusing on optimizing the banner below the navigation menu on this website. My goal is to make it responsive so that the player in the banner remains visible even when scaling down to iPhone size portrait. You can find the code for this secti ...

How can I enable the "edit" function for a button within a list item?

I am currently working on a feature that allows users to edit list rows by clicking a button. However, I am facing an issue where the "edit" button only edits the first row instead of the matched line. This functionality is part of a program I am developi ...

A problem arose with Vitest when attempting to call the tRPC createCaller function due to the presence of incorrect JS syntax within the content. To resolve this issue, it is recommended to include

Currently, I am in the process of writing unit tests with Vitest and utilizing the tRPC createCaller to simulate the trpc context. However, I am encountering a failure during testing which presents the following error message: Error: Failed to parse sourc ...

Place an image in a div so that it is centered both vertically and horizontally

I have been trying to center an image both horizontally and vertically, but it seems like my code is not working properly. Here is what I have so far: #parent { position: relative; float: left; width: 700px; height: 400px; overflow: hi ...

Storing the information received from an API as an HTML element

My HTML file contains JavaScript, along with a URL that displays data retrieved from an AWS lambda API call via AWS API Gateway. The page initially appears blank and the data is structured like this: [ {"user": "bob", "groups": ["bobsGroup"], "policies": ...

Tips for extracting a value from a currently active list item's anchor tag with JQuery on Mapbox API?

Currently, I am attempting to extract the value from a forward geocoder that predicts addresses while a user is typing. My goal is to then send this value to a form with an id of "pickup". However, I am encountering difficulties in capturing the li > a ele ...