1

How to call the input id in javascript using the python class base views?

Javascript:

<script> function myFunction() { var txt = document.getElementById("Plate_no").value; var res = txt.charAt(txt.length-1); document.getElementById("Ending").innerHTML = res; } </script 

And this is my HTML form

<form method="POST"> {% csrf_token %} <div class="col-sm-4"> <label>Plate Number:</label>{{ form.Plate_no }} <button onclick="myFunction()">Get Ending</button> </div> <div class="col-sm-4"> <label>Conduction Sticker Number:</label>{{ form.Conduction_Sticker }} </div> <div class="col-sm-4"> <label>Remarks:</label>{{ form.Remarks }} </div> <div class="col-sm-4"> <label>CR Name:</label>{{ form.CR_name }} </div> <div class="col-sm-4"> <label >Ending:</label>{{ form.Ending }} </div> 
1
  • Possible duplicate here Commented Nov 28, 2019 at 1:37

3 Answers 3

0

In Javascript a string is a char array, hence you can access the last character by the length of the string.

var res = txt[txt.length -1]; 
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, but in my javascript code can't get the input value. It is possible to call the fields since I'm using a class base views?
Assuming you have a proper ID called Plate_no, you can try to instead use innerText, like so var txt =document.getElementById("Plate_no").innerText. That might work.
0

Try this:

function myFunction() { var txt = document.querySelectorAll("input")[0].value; var res = txt.charAt(txt.length-1); document.getElementById("Ending").innerHTML = res; }
<div class="col-sm-4"> <label>Plate Number:</label><input> <button onclick="myFunction()">Get Ending</button> </div> <div class="col-sm-4"> <label>Conduction Sticker Number:</label>{{ form.Conduction_Sticker }} </div> <div class="col-sm-4"> <label>Remarks:</label>{{ form.Remarks }} </div> <div class="col-sm-4"> <label>CR Name:</label>{{ form.CR_name }} </div> <div class="col-sm-4"> <label >Ending:</label><div id="Ending">{{ form.Ending }}</div> </div>

Comments

0

When using the getElementById() function, you need to have an id="" attribute on the element you want to select.

<label> Plate Number: </label> <span id="plate_no"> {{ form.Plate_no }} </span> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.