I have a function in JavaScript that submits a message to a method in a Grails controller and at the same time updates div with myID id.
function messageKeyPress(field,event,messageBox) {
...
var message = $('#messageBox').val();
<g:remoteFunction action="submitMessage" params="\'message=\'+message" update="myID"/>
...
}
I use it like this:
<div id="chatMessages" class="chatMessages"></div>
<input type="text" id="messageBox" class="messageBox" name="message" onkeypress="messageKeyPress(this,event,'#messageBox');"/>
<div id="myID">
I would like that function to be reusable being able to update different divs.
I tried:
onkeypress="messageKeyPress(this,event,'#messageBox', '#myID');"
and in JavaScript:
function messageKeyPress(field,event,messageBox, myID) {
...
<g:remoteFunction action="submitMessage" params="\'message=\'+message" update="${myID}"/>
But that didn't work. My question is how to pass a JavaScript variable to Grails g:remoteFunction "update" property.
I suggest you to use jQuery instead. It is bundled by default to Grails projects. As a result, you'll get a neat separation between javascript code and gsp view logic. For instance, application.js might look like this:
(function($) {
$('.messageBox').on('keypress', function () {
...
var params = {message: $(this).val()};
var url = $(this).data('url');
var target = $(this).data('target');
$.post(url, params, function(response) {
$(target).html(response);
});
...
});
})(jQuery);
and your view file:
<input type="text" id="messageBox"
class="messageBox" name="message"
data-url="${createLink(action: 'submitMessage')}"
data-target="#myId"/>
<div id="myID"></div>
You should assign a messageBox css class to every input field you want to have this event listener. And in data-target attribute of every field you can specify a selector for all divs that should be updated.
jQuery is very easy to learn. http://api.jquery.com/
The update attribute should be set to the ID of the element to be updated, not a selector that matches this element. In other words, try this:
onkeypress="messageKeyPress(this,event,'#messageBox', 'myID');" // '#' removed from myID
Related
i would like to get the value of an <input type="text"> that was created dynamically inside a modal and put it into variable "newcomment".
This is how i make the input:
var newcomment;
var p = $("<p>");
p.append("Some text");
p.append("</p>");
p.append("<input type='text'id='comment_text' value='Comment'"+"onblur=newcomment=$('#comment_text').val()"+" onfocus=if(this.value==this.defaultValue)this.value=''>"+"</input>");
$("div.modal-body").append(p);
The problem is when i write something like "ok" inside the textbox in the modal, and after i focusout from the textbox: newcomment seems not update to "ok" and still have the default "Comment" value.
1st: You need to use newcomment=this.value instead of newcomment=$('#comment_text').val()
2nd: No need to add + signs in your input html code while you not trying to concatenate string by putting variables to it
var newcomment;
var p = $("<p>");
p.append("Some text");
p.append("</p>");
p.append("<input type='text' id='comment_text' value='Comment' onblur='newcomment=this.value; alert(newcomment);' onfocus=if(this.value==this.defaultValue)this.value='' />");
$("body").append(p);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Not really the answer here, but might help you get at the root of the problem.
JS:
var newComment, defaultValue;
function doOnBlur(){
newComment = $('#comment_text').val()
}
function doOnFocus(){
if($('#comment_text').val() == defaultValue){
$('#comment_text').val('')
}
}
HTML:
<input type='text' id='comment_text' placeholder='Comment' onblur='doOnBlur()' onfocus='doOnFocus()' />
<!-- inputs dont have a close tag, also should use placeholder for temporary text -->
from here, you can set breakpoints in the debugger and see where your code is going wrong. You can also modify the functions much more easily rather than writing the executing code in the HTML
I am developping a website with some serious Javascript involved and I have to use generated data from PHP in my JS code.
For example, to be able to use my page ID in JS, I proceed like this:
<input type="hidden" id="pageId" value="<?php echo $page->getId() ?>" />
<button id="runJs">RUN</button>
And in my javascript (with jQuery):
$(function() {
$('#runJs').click(function() {
var id = $('#pageId').val();
});
});
It works, but is there a cleaner way to do it?
Since HTML5, one can now add user-made attributes to any HTML tag as long as it starts with data-.
In HTML5:
<button id="runJs" data-pageId="<?php echo $page->getId() ?>">RUN</button>
In JS:
$(function() {
$('#runJs').click(function() {
var id = $(this).attr('data-pageId');
});
});
Or, as said Eric Martinez in the comments, using jQuery:
var id = $(this).data('pageId');
Passing data this way is cleaner for two reasons:
It is not using a side tag that could be confusing.
The data you pass is included in the button, which means another button with its own data-XXX can use the same JS function, even on the same page.
Example
HTML:
<button data-value="5">Square it!</button>
<button data-value="7">Square it!</button>
<button data-value="12">Square it!</button>
JS:
$(function() {
$('button').click(function() {
var value = $(this).attr('data-value');
alert(value * value); // Shows 25, 49 or 144 depending of the button pressed.
});
});
The function doesn't know the button. The buttons don't even need an ID as long as JS is involved.
You can create variables inside the tag. Like this:
<script>
var pageId = '<?php echo $page->getId(); ?>';
</script>
Later in your script:
$(function() {
$('#runJs').click(function() {
var id = pageId;
});
});
I have this template event:
'click .edit_user_button': function(ev){
ev.preventDefault();
var id = this._id;
var children = $("'#" + id + "'");
console.log(children);
children.css('display', 'inline-block');
}
That I want to target this input:
<input class='user_input form-control edit_fields' id='username_field {{_id}}' type="text" name='username' placeholder="username">
but I can't get it to work. The template has scope, and this._id matches {{_id}} in the template.
Is children supposed to be the variable that targets the input ?
This is just elementary jQuery.
var input = $('input[username]').val();
This is not the meteor way to do manual DOM manipulation. If you want a class on an element to be dynamic, just write a helper function to return that class from a reactive variable (collection, session or reactiveVar). For example, for an input to be disabled reactively, do this:
<input id="chopoffthehead" disabled={{isDisabled}}/>
helper function:
isDisabled: function() {
return Session.get('isCreatureHydra');
}
This way, whenever the session variable isCreatureHydra is set to true, the input will be disabled.
I have made a dataTable and populated it with many fields, but I would like to add my own search/filter function to it.
I have a textbox that I am using as the search/filter:
<div class="filterTable">
<form>
<input id="tableSearch" type="text" placeholder="filter">
</form>
</div>
And this is the JavaScript function that I have added for it:
$("tableSearch").keyup(function () {
var string = document.getElementById("tableSearch").value;
oTable.fnFilter(string);
});
oTable is the initialized dataTable.
The problem I am having is that the JavaScript function is never hit. Any Ideas?
You should use the # tag for reffering the ID of an element.
Try with the below mentioned code.
$("#tableSearch").keyup(function () {
var string = $(this).val();
oTable.fnFilter(string);
});
I am sure this is so easy and I'm just a huge huge noob. I have a form on a PHP page, and it has a few normal form elements (1 textarea, 1 text field).
I am also dynamically adding 100 small images to the page, which are random, and I am using JQuery to let someone select or deselect these images:
Here is the html that loops 100 times to display the images:
<div class='avatar'><img class='avatar_image' src='$this_profile_image' name='$thisfriend'></div>
and here is the Jquery:
<script type="text/javascript">
$(document).ready(function() {
$(".avatar_image").click(function() {
$(this).toggleClass("red");
});
});
</script>
What I want to do is, when the form is submitted, have the script that processes it be able to tell which of those 100 images is selected (so it's class will be "red" instead of "avatar_image"). I am blanking on this.
You'll need to add hidden inputs with some kind of identifiers for those images, and toggle the state of those inputs based on the image selected-ness. Something like this:
Change your image markup:
<div class='avatar'>
<img class='avatar_image' src='$this_profile_image' name='$thisfriend'>
<input type="hidden" name="avatar_image[]" value="$this_profile_image" disabled="disabled" />
</div>
Change jQuery binding (and use event delegation, maybe pick a better container than document.body):
<script type="text/javascript">
$(function() {
var selClass = 'red';
$(document.body).on('click', ".avatar_image", function() {
var $this = $(this);
var $inp = $this.siblings('input[type="hidden"]');
var isSelected = $this.hasClass(selClass), willBeSelected = !isSelected;
$this.toggleClass(selClass);
if(willBeSelected) {
$inp.removeAttr('disabled');
} else {
$inp.attr('disabled', 'disabled');
}
});
});
</script>
Read the submitted data in PHP (assuming you're submitting via a POST form):
$selectedImages = $_POST['avatar_image'];
Add a ID to each image, when its clicked grab the id and then inject it into a hidden textfield
<input type="hidden" name="avatar" id="avatar" value="" />
$(".avatar_image").click(function() {
$(this).toggleClass("red");
//assign its id to the hidden field value
$("input[name='avatar']").attr('value', $(this).attr('id'));
// pass that to your DB
});
I presume your using ajax to grab this data back
success : function(callback){
$("image[id*='"+callback.avatar+"']").addClass('red');
}
Try this
PHP: Add the id for the friend to the html you had
<div class='avatar'>
<img class='avatar_image' src='$this_profile_image' name='$thisfriend' data-id='$thisFriendsId>
</div>
JS: Create an empty array. Use each function to go through push the selected id into your array. Then use post to submit to your php.
selected = [];
$(function(){
$(".avatar_image").click(function() {
$(this).toggleClass("red");
});
$('.submit').click(function(){
$('.red').each(function(){
var selectedId = $(this).data('id');
selected.push(selectedId);
});
$.post ('http://mysite.com/process.php', selected, function() { alert('succes!'); });
});
});