The function document.getElementById is unable to retrieve the input value

I am attempting to extract the content of an input using document.getElementById. It successfully retrieves other values, but it fails specifically for this one.

let title_input = document.getElementById('HomeworkTitle').value;
is what I'm trying to accomplish in order to utilize it here:

function saveHomework() {

        let title_input = document.getElementById('HomeworkTitle').value;
        let image_input = document.getElementById('image').value;
        let progress_input = document.getElementById('progress').value;
        let description_input = document.getElementById('description').value;
        let duedate_input = document.getElementById('duedate').value;

        axios.post('/storeHomework', {

            subject_id: {{ $id->id }},
            title: title_input,
            image: image_input,
            progress: progress_input,
            description: description_input,
            duedate: duedate_input

        }).then((response) => {

            console.log(response)
            $("#exampleModal .close").click();

        }).catch((error) => {

            console.log(error.response.data)

        });
        $('#thisdiv').load(document.URL +  ' #thisdiv');
    }

    saveHomework();

The HTML code captures:

<div class="form-group">
                <label for="exampleInputEmail1">Title:</label>
                <input type="text" name="HomeworkTitle" id="HomeworkTitle" class="form-control" aria-describedby="help">
                <small id="help" class="form-text text-muted">Ex: Investigate blah blah blah.</small>
            </div>  

            <div class="form-group">
                <label for="exampleInputEmail1">Description:</label>
                <textarea type="text" name="description" id="description" class="form-control" aria-describedby="help"></textarea>
                <small id="help" class="form-text text-muted">Point out here details about the homework (optional).</small>
            </div> 

            <div class="input-group mb-3 px-2 py-2 rounded-pill bg-white shadow-sm">
                <input id="image" type="file" name="image" onchange="readURL(this);" class="form-control border-0">
                <div class="input-group-append">
                    <label for="upload" class="btn btn-light m-0 rounded-pill px-4"> <i class="fa fa-cloud-upload mr-2 text-muted"></i><small class="text-uppercase font-weight-bold text-muted">Choose file</small></label>
                </div>
            </div>

             <div class="form-group">
                <label for="exampleInputEmail1">Deadline:</label>
                <input class="form-control" type="date" id="duedate" name="duedate">
            </div> 

            <div class="form-group">
                <label for="exampleInputEmail1">Current progress:</label>
                <div class="range-slider">
                    <input class="range-slider__range" type="range" value="0" min="0" max="100" step="10" id="progress" name="progress">
                    <span class="range-slider__value">0</span>
                </div>
            </div> 
</div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary btn-submit" onclick="saveHomework()">Add Homework</button>
      </div>
    </div>

The reason behind the malfunction remains unclear.

Answer №1

Assuming that your JavaScript file is correctly connected to your HTML document, attempt the following code snippet:

document.getElementById("HomeworkTitle").value;

Answer №2

Please review the following code for accuracy and completeness:

  var title_input = ''
        let check = document.getElementById("HomeworkTitle")
        check.addEventListener("focusout", myFunction);

        function myFunction() {
        title_input = check.value
          console.log(check.value)
        }
    /////////////here you can you variable//////////////////
    //axios.post('/storeHomework', {
    //console.log('title_input',title_input)
                //title: title_input, //here
       // }

function saveHomework() {
        let image_input = document.getElementById('image').value;
        let progress_input = document.getElementById('progress').value;
        let description_input = document.getElementById('description').value;
        let duedate_input = document.getElementById('duedate').value;

        axios.post('/storeHomework', {

            subject_id: {{ $id->id }},
            title: title_input,
            image: image_input,
            progress: progress_input,
            description: description_input,
            duedate: duedate_input

        }).then((response) => {

            console.log(response)
            $("#exampleModal .close").click();

        }).catch((error) => {

            console.log(error.response.data)

        });
        $('#thisdiv').load(document.URL +  ' #thisdiv');
    }

    
 
<div class="form-group">
                <label for="exampleInputEmail1">Title:</label>
                <input type="text" name="HomeworkTitle" id="HomeworkTitle" class="form-control" aria-describedby="help">
                <small id="help" class="form-text text-muted">Ex: Investigate blah blah blah.</small>
            </div>  

            <div class="form-group">
                <label for="exampleInputEmail1">Description:</label>
                <textarea type="text" name="description" id="description" class="form-control" aria-describedby="help"></textarea>
                <small id="help" class="form-text text-muted">Point out here details about the homework (optional).</small>
            </div> 

            <div class="input-group mb-3 px-2 py-2 rounded-pill bg-white shadow-sm">
                <input id="image" type="file" name="image" onchange="readURL(this);" class="form-control border-0">
                <div class="input-group-append">
                    <label for="upload" class="btn btn-light m-0 rounded-pill px-4"> <i class="fa fa-cloud-upload mr-2 text-muted"></i><small class="text-uppercase font-weight-bold text-muted">Choose file</small></label>
                </div>
            </div>

             <div class="form-group">
                <label for="exampleInputEmail1">Deadline:</label>
                <input class="form-control" type="date" id="duedate" name="duedate">
            </div> 

            <div class="form-group">
                <label for="exampleInputEmail1">Current progress:</label>
                <div class="range-slider">
                    <input class="range-slider__range" type="range" value="0" min="0" max="100" step="10" id="progress" name="progress">
                    <span class="range-slider__value">0</span>
                </div>
            </div> 
</div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary btn-submit" onclick="saveHomework()">Add Homework</button>
      </div>
    </div>

Answer №3

Have you encountered an error message? It's possible that your input is empty, which could be why you're not receiving any output.

function saveHomework() {
    const title = document.getElementById("HomeworkTitle");
    console.log(title.value)
}
<input type="text" id="HomeworkTitle" value="somevalue">
<button onclick="javascript:saveHomework()">save</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

Ways to update div using jquery without creating copies

I have a code snippet that refreshes a div every 10 seconds: <script type="text/javascript> setInterval(function(){ $('#feed').load('forum.php #feed').fadeIn("slow"); }, 10000); </script> It works well, but there is one is ...

Struggling to place buttons below each row in a Bootstrap DataTable, unfortunately, they are only appearing under a specific column rather than the entire row

I have developed a system for managing event expenses that includes an option for multiple installments of a single payment for each event. My goal is to display these installments when a user hovers over an event in the table, with each row representing a ...

Complete and submit both forms during a single event

Essentially, I have an event called onclick that takes form data and stores it in a variable. When another function is executed by the user, I want to send that variable through ajax within the function. This is the onclick event (first form): $('#n ...

What is causing the width discrepancy in my header section on mobile devices?

Help needed with website responsiveness issue! The site works fine on most screen sizes, but when it reaches around 414px in width, the intro section becomes too wide for the screen. Any ideas on what could be causing this problem? html: <nav id="m ...

"Production environment encounters issues with react helper imports, whereas development environment has no trouble with

I have a JavaScript file named "globalHelper.js" which looks like this: exports.myMethod = (data) => { // method implementation here } exports.myOtherMethod = () => { ... } and so forth... When I want to use my Helper in other files, I import it ...

Launching Toasts with Bootstrap 4

I've been working with toasts in Bootstrap 4 and one thing has been bothering me: When I initialize the toast like this: <div class="toast my-3" data-delay="2500"> <div class="toast-header text-dark"> //fill this later &l ...

Encasing a drop-down menu within a personalized container

I am looking to create a custom HTML element that mimics the behavior of the native <select> element but also triggers a specific update function whenever an attribute or child node is modified. This is essential for incorporating the bootstrap-selec ...

Leverage the power of npm packages within a Flutter mobile app's webview

I am currently developing a Flutter mobile app and I am interested in incorporating an npm package that utilizes web3.js and offers additional custom features. My understanding is that Dart code in Flutter is not compiled to JavaScript, so I have been lo ...

What is preventing me from changing the text color of this span element to white?

For some reason, I'm trying to make the first two texts of each line appear in white, but my CSS doesn't seem to affect the span elements generated by JavaScript. Take a look at the code snippet below for more details. I'm still learning ho ...

The textfields within the .map are not aligned next to each other

Adding the .map caused the name and quantity text fields to no longer display side by side. Before adding the .map, these two fields were in the same row but now they are not. <Grid container rowSpacing={1} columnSpacing={{ xs: 1, sm: 2, md: 3 }}> ...

Setting a displacement/normal map for only one face of a cylinder

My current setup involves creating a cylinder using the following code: var geometry = new THREE.CylinderGeometry( 50, 50, 2, 128 ); The resulting shape is a flat cylinder resembling a coin. However, when I apply a displacementMap and normalMap, I notice ...

Are there any other methods of using HREF in an <asp:Button> besides OnClientClick for invoking an inline div?

I decided to create a concealed <div> on the same page and tried calling it with href="#", which worked perfectly. However, when I attempted to use the same code in ASP.net, I encountered some issues with Javascript or other factors that prevented it ...

Have you considered retrieving POST parameters using Ajax POST in jQuery?

Below is the code snippet: $.ajax({ type: "POST", url: "http://localhost:3000/rcm/global_config/update", data: {k: 'sdfa', v: 'dsfas'}, success: function(data, textStatus, XMLHttpRequest){ alert("Data ...

Configuring timezone for 'date' type in Plotly.js

I'm currently working on a graph to showcase the trend over time. The data I have is in Unix format and I use JavaScript code (new Date(data)).toUTCString to display it in my title. Surprisingly, while the data for the graph and the title is the same, ...

Encountering a "Cannot GET /PATH" error while developing a NUXT application due to a DOT present in

In my nuxt application, I encountered a peculiar issue. When I execute npm run dev, everything functions properly. However, after running npm run build and then npm run start, I face the error message stating cannot GET [path of the page here] I noticed t ...

Using ThreeJs and TweenJS to insert a delay between tweens using a for loop

Struggling with animating a bin packing problem using Three.JS and Tween.JS. I am having difficulty getting the animation to play successively rather than all at once within my loop. Attempting to use the setTimeout solution has not been successful. Does a ...

FireFox is unresponsive to OPTIONS requests

I have a webpage that is accessed through HTTP. The client-side code is making AJAX requests for authorization to the same domain, but using HTTPS, which causes CORS issues. When using FireFox, the request looks like this: // domains and cookies are chang ...

Guide to transmitting webcam feed from server to servlet

I am trying to display the webcam connected to my server in a servlet. I have come across suggestions to use getUserMedia();, however, this only captures the user's video webcam feed and not the server's. Is there a way to achieve this? My servl ...

JavaScript issue causing unexpected behavior in top and left positions

I've been experiencing an issue with my JavaScript code on an HTML file. Despite changing the top or left values, the image does not move as expected. I've spent hours searching for a solution and even tried copying tons of different code snippet ...

Understanding the Use of Promises and Async/Await in Typescript

Struggling with asynchronous libraries in Typescript, I find myself looking for a way to wait for promises to be resolved without turning every method into an async function. Rather than transforming my entire object model into a chain of Promises and asyn ...