How can I invoke a JavaScript function from an HTML file and send a parameter along with it?

I'm using JavaScript to calculate the total value in a field by adding ca, part_a, and part_b numbers. The GPA is also calculated through JavaScript. In the first row, I can get the Total and GPA values with JavaScript, but in the second and subsequent rows, I cannot retrieve them. How can I solve this issue?

<div>
    <ul class="breadcrumb">
        <li>
            <a href="#">Home</a> <span class="divider">/</span>
        </li>
        <li>
            <a href="#">Forms</a>
        </li>
    </ul>
</div>

<div class="row-fluid sortable">
    <div class="box span12">
        <div class="box-header well" data-original-title>
            <h2><i class="icon-edit"></i>Add All Student Mark</h2>
            <h3>

            </h3>
            <div class="box-icon">
                <a href="#" class="btn btn-setting btn-round"><i class="icon-cog"></i></a>
                <a href="#" class="btn btn-minimize btn-round"><i class="icon-chevron-up"></i></a>
                <a href="#" class="btn btn-close btn-round"><i class="icon-remove"></i></a>
            </div>
        </div>
        <div class="box-content">
            <form class="form-horizontal" action="<?php echo base_url();?>super_admin/save_all_student_mark" method="post" enctype="multipart/form-data">
                <fieldset>
                    <legend>Add all Student Mark</legend>
                    <h3>
                        <?php
                        $msg = $this->session->userdata('message');
                        if ($msg) {
                            echo $msg;
                            $this->session->unset_userdata('message');
                        }
                        ?>
                    </h3>




                    <div class="box-content">
                    <table class="table table-striped table-bordered bootstrap-datatable">
                        <thead>
                            <tr>
                                <th>Student Roll</th>
                                <th>CA</th>
                                <th>Part A</th>
                                <th>Part B</th>
                                <th>Total</th>
                                <th>GPA</th>
                            </tr>
                        </thead>   
                        <tbody>
                            <?php $i=0;?>
                            <?php foreach($student_info_by_session as $student_info){?>
                            <tr>
                                <td>
                                    <input type="text" class="span12 typeahead"  value="<?php echo $student_info->student_roll; ?>">
                                    <input type="hidden" class="span12 typeahead" name="data\[<?php echo $i; ?>\]\[student_id\]"  val...

Answer №1

To address the first part of your inquiry, you can achieve this by utilizing the event method to call your function.

For instance:

function myFunction() {
    document.getElementById("demo").innerHTML = "Hello World";
}
<p>Click the button to trigger a function that will output "Hello World" in a p element with id="demo".</p>

<button onclick="myFunction()">Click me</button>

<p id="demo"></p>

Alternatively, you can utilize a JavaScript event listener.

For example:

document.getElementById("myBtn").addEventListener("click", displayDate);

function displayDate() {
    document.getElementById("demo").innerHTML = Date();
}
<p>This example uses the addEventListener() method to attach a click event to a button.</p>

<button id="myBtn">Try it</button>

<p id="demo"></p>

You can also opt for using a jQuery event listener.

Example:

$(document).ready(function(){
    $("p").click(function(){
        alert("The paragraph was clicked.");
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Click on this paragraph.</p>

Concerning the second part of your query, you have the option to pass parameters when calling your function or retrieve them while inside the function.

An example of passing parameters when calling the function:

function changeText(id) {
    id.innerHTML = "Ooops!";
}
<h1 onclick="changeText(this)">Click on this text!</h1>

An illustration of retrieving parameters within the function (in JavaScript):

function myFunction() {
    var x = document.getElementById("myText").value;
    document.getElementById("demo").innerHTML = x;
}
First Name: <input type="text" id="myText" value="Mickey">

<p>Click the button to display the value of the value attribute of the text field.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

For extracting parameters within the function (using jQuery):

$(document).ready(function(){
    $("button").click(function(){
        var first_name = $("#user_f").val();
        var last_name = $("#user_l").val();
        var name = first_name + " " + last_name;
        $("#user").val(name);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> First Name: <input type="text" id="user_f"></p>

<p> Last Name: <input type="text" id="user_l"></p>

<p>Name: <input type="text" id="user"></p>

<button>Set the value of the input field</button>

If you require a server-side variable, you can utilize this approach. In your JS function, use

var x = <?php echo $valor_x; ?>;
. This method is applicable when your PHP code resides on the same page as your JS.

Answer №2

You seem to have numerous elements (one per row) labeled with IDs such as total\[\]. Despite not having aesthetically pleasing IDs (symbols shouldn't be included in IDs), they are not unique, which is essential for IDs! Consider renaming them to something like total-<?php echo $i; ?> for better clarity.

Furthermore, your copy_text function seems to be defined multiple times (once for each PHP loop, based on the PHP output), leading to errors. It might be beneficial to create a single-parameter function, e.g. copy_text(id), and define it outside the loop. If this sounds complex, you can opt to keep it as is but assign distinct names to each function, like

copy_text_<?php echo $i; ?>
.

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

Load texture using ImageUtils with callback in Canvas Renderer

Currently, I am utilizing three.js revision 53. While attempting to load a texture in Canvas Renderer (specifically on Win7) and incorporating a callback for the onLoad event, the texture fails to display. Surprisingly enough, removing the callback functi ...

Implementing Vuejs Array Push in Separate Components

I am attempting to extract data from an object and store it in an array using Vue. My goal is to have each value stored in a separate array every time I click on an item. Each click should push the todo into a different array. How can I achieve this separa ...

Is there a way in React to specify which properties to pass (and when to pass them) to child components based on the properties of the parent component?

In this hypothetical scenario, there are 4 components already in place: MainComponent1, MainComponent2, IntermediateComponent, and ChildComponent. Both MainComponent1 and MainComponent2 can utilize IntermediateComponent as their child component, while Chil ...

Kendo UI Scheduler: The system encountered an overflow while converting to a date and time format

Working on a project using .NET MVC and the Kendo UI Scheduler, an open-source tool. The goal is to save, read, update, and delete events from the scheduler into the database using JavaScript. Encountering some challenges in the process - when attempting ...

404 error occurs when AngularJS removes hash symbol from URLs

I successfully eliminated the hash from my Angular JS website using the following code snippet: $locationProvider.html5Mode(true); Now, the previously displayed URL has been replaced with . The issue I'm facing is that when I do a hard refresh (Ct ...

Learn the process of transmitting data from middleware to components and APIs in Next.js version 13

I've been experimenting with the Next Js 13 middleware feature and I'm a bit confused about how to pass data from the middleware to components/pages/api. For example, when trying to pass payload data or determine who the currently logged-in user ...

I am interested in using a loop in Angular to highlight my div element

Enhancing my comprehension regarding the mentioned images. If I don't select anything within the div property, the default style (css) should appear like this, at least when one div is selected. However, the issue arises when unable to select. This ...

Troubleshooting problems encountered when duplicating an array in JavaScript

I am attempting to utilize properties and flatmap to modify an array without altering the original data. I have implemented this method in two different instances within a single dispatch call in Vue.js when transferring data from parent to children comp ...

What is the best way to choose a random text from a dropdown menu that contains several div elements using Playwright?

web element Is it possible to choose a "random" text using div tags from a dropdown? I am attempting to pick any random country from the dropdown with the following code in Playwright: const selectCountry = this.page.locator('<this locator>&apos ...

How do I iterate through my state in React Redux?

Currently, I am delving into Redux by creating a to-do list in React. I have been pondering on the utilization of the map function to iterate over the state so that I can display the data stored within different div elements. Here is my initial state: cons ...

Numerous textareas fail to function properly according to JQuery's standards

Need help with resizing multiple textarea elements dynamically as the user types in them (on the Y-axis). Currently, I have code that successfully resizes a single textarea, but it does not work when there are multiple textareas on the page. Here is the c ...

Refining an array data table within a nested component

Transitioning my old PHP/jquery single-page applications to VueJS/Webpack has been a journey I'm undertaking to familiarize myself with the latter technology. It involves converting a simple table that pulls data from a JSON API and incorporates filte ...

Exploring the World of Infinite Scrolling with React.js and Material_ui

I am currently working on a project using react.js As part of this project, I need to implement a board with infinite scroll similar to Facebook I have a specific question regarding this implementation. When scrolling the board and loading more posts li ...

Tips for including a Places Autocomplete box within an InfoWindow on Google Maps

I am currently working with the Google Maps Javascript API v3 and I am facing a challenge. I want to integrate a Places Autocomplete box inside an InfoWindow that pops up when a user clicks on a marker. I have successfully created an autocomplete object a ...

Assistance with the JQuery Validation Plugin

Currently, I am utilizing the JQuery validation plugin to validate a form. However, in addition to displaying an error message, I also want it to modify the CSS for the td element above it. This is my current implementation: function handleValidationError ...

Issue with Ant Design form validation

After reading through the documentation, I attempted to implement the code provided: Here is a basic example: import { Button, Form, Input } from "antd"; export default function App() { const [form] = Form.useForm(); return ( <Form f ...

Is it possible to create a button function in HTML that can alter the CSS image tag?

Is there a way I could create a function that can retrieve a value, update an image source, and then incrementally select another value? It would be incredibly helpful if you could provide a reference where I could learn how to do this or explain it in det ...

Failed AJAX Request - Google Chrome Experiences Issue

I have been working on a website that loads HTML content from a template page and then pulls in data from an XML file. This process is initiated in the document.ready function as shown below: $.ajax({ type : "GET", url : "t ...

Developing with PHP and Ajax with the onchange event handler

This is the code snippet from my cat.php file: <script> function showUser(str) { if (str=="") { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlh ...

What are some best practices for integrating jointjs with reactjs?

Could the jointjs library be utilized alongside reactjs? Are there any libraries or wrappers that facilitate this integration? If not, what is the most straightforward method to incorporate it? ...