Fill input field, with twig value using jquery - javascript

I've been searching for a while with no luck.
I know my question looks mundane, and it has plenty (as in hundreds) of answers out in google and here, yet, still my problem seems far from solved.
I have the following problem, I need to fill an input field, with a value from silex variables in a twig file.
the form is as follows:
<span>Author: </span>
<input type="text" name="author" id="author"
{% if user.getAuthorName %}value="{{user.getAuthorName}}"{% endif %} />
<span>Use your own username</span>
and the js code is:
<script>
$(function(){
$('#filler').live('click', function() {
$("#author").val($("#author").text("{{user.getFirstName}} {{user.getLastName}}"));
});
});
</script>
the problem I'm having is, the code actually works, yet still, when i click, it fills the field with
[object Object]
instead of the actual value of the 2 variables
I've tried changing it to a hidden field with an id, and setting the variables as value, and using
.text($("#idfield").val())
still no luck, still fills the values with
[object Object]
has any of you any idea what I'm doing wrong here?

You should remove the double declaration:
$("#author").val("{{user.getFirstName}} {{user.getLastName}}");

Here is a bit cleaned up version of your code with no live as it's deprecated/removed.
$(function() {
$('#filler').on('click', function(e) {
e.preventDefault();
//If your JS is parsed as a twig template then, you could use
$("#author").val("{{user.getFirstName}} {{user.getLastName}}");
//and remove the data-full-name from your HTML
//If not, keep the data-full-name and use:
$("#author").val($("#author").data("fullName"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>Author: </span>
<input data-full-name="{{user.getFirstName}} {{user.getLastName}}" type="text" name="author" id="author" value="{% if user.getAuthorName %}{{user.getAuthorName}}{% endif %}" />
<span>Use your own username</span>

Related

How can I call functions using onkeypress-events in EJS file?

I'm trying to accomplish a live character counter for a text input field, but cannot seem to make it work. The onkeypress-function either go as undefined or is just called once when loading the page
Simply assigning the function with onkeypress=" " does not seem to work.
Additionally, I want to update the text of charcountLabel; which I cannot seem to do. Simply using 'document.getElementById' for updating its innerHTML does not work.
How do I correctly assign keypress-functions to html-elements in .ejs?
How do I access and update innerHTML of other elements?
See code below:
<input type="text" id="textContent" onkeypress="charcount">
// Should be live-updated with the length of input text above.
<span id="charcountLabel"> 0 </span>
<script>
function charcount() {
var characterCount = document.getElementById("textContent").innerText.length;
document.getElementById("charcountLabel").innerHTML = characterCount;
}
</script>
Here you are
<input type="text" id="textContent" onkeypress="charcount()">
<!-- Should be live-updated with the length of input text above. -->
<span id="charcountLabel">0</span>
<script>
function charcount() {
var characterCount = document.getElementById("textContent").value.length;
document.getElementById("charcountLabel").innerHTML = characterCount;
}
</script>
Use parenthesis () to call the function and replace innerText with value property.
Note that // is comment in Javascript, not in html where you should use <!-- your comment --> instead.
Last, it has nothing to do with ejs.

Webserver PLC Siemens Javascript, when click, set value

I have a dropdown menu and want to write data to a field when clicked. I have tested it with regular tags but I am having trouble with the syntax when I am testing a tag from a PLC that is named 'mytag' with these '' around it .
In the HTML document, I have to tell the program that the particular tag is both read and write by doing this:
<!-- AWP_In_Variable Name="webdata".'mytag' -->
'"webdata".mytag' is a tricky name, so I made an alias named 'mytag':
<!-- AWP_In_Variable Name="webdata" -->
<!-- AWP_In_Variable Name='Fortype' Use='"webdata".mytag' -->
Here is an example for a typical application of the tag where it works using it:
:=mytag:
<form method="post">
<input name='mytag' type="text" size=2 />
<button type="submit">Save</button>
</form>
The code for setting values by click works with regular tags like this:
$("#id_from_dropdown_menu").click(function() {
$("#myval").html("10");
});
But the code does not work when I try to use 'mytag', I think it is because of the '' signs.
$("#id_from_dropdown_menu").click(function() {
$("#mytag").html("10");
});
ANY TIPS?
NO worries! Figured it out. Leave post of you get similar problems :)

replace parameter using jquery

I'm working with python and jinja. When I render template I sent two parameters like this :
return render_template('mod_page/index.html',
types_first = utils.questions_first(),
types_second = utils.questions_second())
questions_first and questions_second are two same functions, something like this:
def questions_first(self):
return ['Name','Surname', 'Phone']
In index page I have a tag like this:
<html lang="en">
...
I want to take lang attribute with jQuery and then to check if it is 'en' I want to use questions_first if it is 'sr' I want to use questions_second.
My question is how can I replace the parameter types_first inside jinja code or put there, I don't know exactly what to do, I tried to do it like this:
<script>
$(document).ready(function(e){
var language = $('html').attr('lang');
var selectedFunction;
if(language == "sq"){
selectedFunction = "sq";}
else{
selectedFunction = "sr"; }
</script>
....
<p> Questions: </p>
{{ _({% for type in types_first %}) }}
<div class="checkbox">
<label><input type="checkbox" value="{{ type }}">{{ type }}</label>
</div>
{% endfor %}
First solution (better):
If you want to change lang, you can use i18next framework (http://i18next.com/docs/). It's much simpler solution.
Second solution (worse):
Select via jQuery element you want to change -> use empty() function -> render element with changed values and assign it to selector with append()
You can also combine both solutions. Write function to rerender template and change dynamically langauge. e.g.:
fn_or_elt.empty();
fn_or_elt.append(markup);
fn_or_elt.i18n();

Uncaught TypeError: Cannot set property 'value' of null

I'm trying to pass the entered text to the controller using an ajax request. But i'm getting athe error "Uncaught TypeError: Cannot set property 'value' of null " when I tried to execute JS file..
Here is the HTMLcode:
<form action="">
<input type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item..." value="text" />
<input type="button" class="searchbox_submit1" name="submit" value="text" onClick="javascript:getSearchText();">
</form>
Here is the JS code:
function getSearchText() {
var searchText = document.getElementByName("search").value;
h_url=document.getElementById("u").value;
var theURL = h_url+'search_all/' + deptid + '/' + searchText + '/1';
$.ajax({
url : theURL,
fail: function(){
},
success : function() {
},
error:function(){
}
});
}
Please help me to fix this.
You don't have an element with the id u.That's why the error occurs.
Note that you are trying to get the value of the input element with the name 'u' and it's not defined in your code.
The problem may where the code is being executed. If you are in the head of a document executing JavaScript, even when you have an element with id="u" in your web page, the code gets executed before the DOM is finished loading, and so none of the HTML really exists yet... You can fix this by moving your code to the end of the page just above the closing html tag. This is one good reason to use jQuery.
In case anyone landed on this page for a similar issue, I found that this error can happen if your JavaScript is running in the HEAD before your form is ready. Moving your JavaScript to the bottom of the page fixed it for my situation.
The problem is that you haven't got any element with the id u so that you are calling something that doesn't exist.
To fix that you have to add an id to the element.
<input id="u" type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item..." value="text" />
And I've seen too you have added a value for the input, so it means the input is not empty and it will contain text. As result placeholder won't be displayed.
Finally there is a warning that W3Validator will say because of the "/" in the end. :
For the current document, the validator interprets strings like according to legacy rules that break the expectations of most authors and thus cause confusing warnings and error messages from the validator. This interpretation is triggered by HTML 4 documents or other SGML-based HTML documents. To avoid the messages, simply remove the "/" character in such contexts. NB: If you expect <FOO /> to be interpreted as an XML-compatible "self-closing" tag, then you need to use XHTML or HTML5.
In conclusion it says you have to remove the slash. Simply write this:
<input id="u" type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item...">
I knew that i am too late for this answer, but i hope this will help to other who are facing and who will face.
As you have written h_url is global var like var = h_url; so you can use that variable anywhere in your file.
h_url=document.getElementById("u").value;
Here h_url contain value of your search box text value whatever user has typed.
document.getElementById("u");
This is the identifier of your form field with some specific ID.
Your Search Field without id
<input type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item..." value="text" />
Alter Search Field with id
<input id="u" type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item..." value="text" />
When you click on submit that will try to fetch value from document.getElementById("u").value; which is syntactically right but you haven't define id so that will return null.
So, Just make sure while you use form fields first define that ID and do other task letter.
I hope this helps you and never get Cannot set property 'value' of null Error.
guys This error because of Element Id not Visible from js Try to inspect element from UI and paste it on javascript file:
before :
document.getElementById('form:salesoverviewform:ticketstatusid').value =topping;
After :
document.getElementById('form:salesoverviewform:j_idt190:ticketstatusid').value =topping;
Credits to Divya Akka .... :)
It seems to be this function
h_url=document.getElementById("u").value;
You can help yourself using some 'console.log' to see what object is Null.
h_url=document.getElementById("u") is null here
There is no element exist with id as u
Add defer to your script tag, if it's in header. It will allow your script to execute after the DOM is loaded.
<script src="script.js type="text/javascript"></script>
It should look like this:
<script src="script.js type="text/javascript" defer></script>

Submit form in javascript using form name

I'm dynamically generating forms with hidden input in a webpage using django templates, which should be submitted when clicking on some associated text label. The problem is that I just can't get it to work.
{% for tag in tags %}
<form name="remove_{{ tag }}" id="{{ tag }}" action="/filter" method="post" accept-charset="utf-8">
<input type="hidden" name="remove_tag" value ="{{ tag }}" />
</form>
{{ tag }}
{% endfor %}
<script type="text/javascript">
function remove_tag(tag) {
document.getElementById(tag).submit();
return false;
}
</script>
This code generates the following javascript error: Uncaught TypeError: Cannot call method 'submit' of null
I've also tried submitting the form using
document.forms[tag].submit();
(changing the form name to tag), but receive pretty much the same error but with 'undefined' instead of null.
In the second example, it looks like the javascript function tries to interpret 'tag' as an integer. If I do use an integer it works alright. I could use the forloop.counter used to generate the forms in the first place, but that is kind of ugly and makes the code harder to maintain.
Is there any other, functioning, way of calling submit() on the forms?
Quotes:
{{ tag }}
The "tag" value has to be properly quoted for the Javascript snippet to be syntactically correct.

Categories

Resources