MooTools: How can I replace existing field text with text insert? - javascript

I've been on this one for a while but no luck so far, however I did get emoticons fully working using code for mootools.
Basically, I have a existing field of
<input type="text" class="post_action_input" value="Say Something..." id="emoticons_insert" />
And a image underneath containing
<img onClick="javascript:$('blove2').fancyShow();" src="./images/user_status_emoticon.jpg" width="25" height="25" />
Which triggers a dropdown containing this emoticon DIV that inserts the :alien: text into the field above
<div id="blove2"><img src="./images/smiley/alien.png" alt="" onClick="javascript:$('blove2').fancyHide();" /></div>
<div id="emoticon1" style="display:none;"> :alien: </div>
And it works great. However, what is really messing up our users is that our input field contains "Say Something" that dissapeares upon click, reappears on outer click etc. When they click the emoticon, it appends and produces "Say Something...:alien:" and posts just like that. How can I completely clear "Say Something..." while preserving the :alien: text upon clicking a emoticon? We are using MooTools 1.2.
Field insert Javascript:
<script type="text/javascript">
function get(id) {
return document.getElementById(id);
}
function contentHTML(id, m) {
var obj = get(id),
op = '';
if (m) {
op += obj.innerHTML;
} else if (!m) {
op += (!obj.innerText) ? obj.textContent : obj.innerText;
}
return (op);
}
function InsertText(input, output) {
var text = contentHTML(input, true);
var ele = get(output);
ele.value += text;
}
</script>
Emoticons drop-down JavaScript:
<script type="text/javascript">
window.addEvent('domready', function() {
Element.implement({
fancyShow: function() {
this.fade('in');
this.setStyle('display', '');
},
fancyHide: function() {
this.fade('out');
this.setStyle('display', 'none');
}
});
//$('element').fancyHide(); // FREEZES STATUS INPUT FIELD FOR SOME REASON
});
</script>
In other words, how can onClick insert replace "Say Something..." from the field, and insert :alien: successfully? Thank you very much guys!

Here is a suggestion, with less code.
In this suggestion I use Mootools's OverText, instead of your inline onfocus/onclick/onblur/value which will not work. OverText comes with Mootools More and in the fiddle I used mootools 1.3.
HTML
<input type="text" class="post_action_input" title="Say something..." id="emoticons_insert" />
<img onClick="javascript:$('blove2').fancyShow();" src="/images/user_status_emoticon.jpg" width="25" height="25" />
<div id="blove2">
<img src="/images/smiley/alien.png" data-name=":alien:" class="emoticon" alt="" />
</div>
Mootools
function InsertText(input, output) {
var ele = document.id(output);
ele.value += input;
ele.fireEvent('change');
}
window.addEvent('domready', function () {
Element.implement({
fancyShow: function () {
this.fade('in');
this.setStyle('display', '');
},
fancyHide: function () {
this.fade('out');
this.setStyle('display', 'none');
}
});
// Labels over the inputs.
document.getElements('input').each(function (el) {
new OverText(el);
});
document.getElements('.emoticon').addEvent('click', function () {
var icon_name = this.get('data-name');
InsertText(icon_name, 'emoticons_insert');
this.getParent().fancyHide();
});
});
Demo here

Related

enable buttons in javascript/jquery based on regex match

I'm having trouble getting the match to bind to the oninput property of my text input. Basically I want my submit button to be enabled only when the regular expression is matched. If the regex isn't matched, a message should be displayed when the cursor is over the submit button. As it stands, typing abc doesn't enable the submit button as I want it to. Can anyone tell me what I'm doing wrong? Thank you.
<div id="message">
</div>
<form method="POST">
<input type="text" id="txt" oninput="match()" />
<input type="submit" id="enter" value="enter" disabled />
</form>
<script>
var txt = $("#txt").value();
var PATTERN = /abc/;
var REQUIREMENTS = "valid entries must contain the string 'abc'";
// disable buttons with custom jquery function
jQuery.fn.extend({
disable: function(state) {
return this.each(function() {
this.disabled = state;
});
}
});
$('input[type="submit"]).disable(true);
var match = function(){
if (txt.match(PATTERN)){
$("#enter").disable(false)
}
else if ($("#enter").hover()){
function(){
$("#message").text(REQUIREMENTS);
}
}
</script>
Your code would be rewrite using plain/vanille JavaScript.
So your code is more clean and better performance:
<div id="message"></div>
<form method="POST">
<input type="text" id="txt" oninput="match()" />
<input type="submit" id="enter" value="enter" disabled />
</form>
<script>
var txt;
var enter = document.getElementById('enter');
var message = document.getElementById('message');
var PATTERN = /abc/;
var REQUIREMENTS = "valid entries must contain the string 'abc'";
function match() {
txt = document.getElementById('txt').value;
if (PATTERN.test(txt)) {
enter.disabled = false;
} else if (isHover(enter)) {
enter.disabled = true;
message.innerHTML = REQUIREMENTS;
} else {
enter.disabled = true;
}
}
function isHover(e) {
return (e.parentElement.querySelector(':hover') === e);
}
</script>
If you wanted to say that you want handle the events in different moments, your code should be the following.
Note: the buttons when are disabled doesn't fired events so, the solution is wrapper in a div element which fired the events. Your code JavaScript is more simple, although the code HTML is a bit more dirty.
<form method="POST">
<input type="text" id="txt" oninput="match()" />
<div style="display: inline-block; position: relative">
<input type="submit" id="enter" value="enter" disabled />
<div id="buttonMouseCatcher" onmouseover="showText(true)" onmouseout="showText(false)" style="position:absolute; z-index: 1;
top: 0px; bottom: 0px; left: 0px; right: 0px;">
</div>
</div>
<script>
var txt;
var enter = document.getElementById('enter');
var message = document.getElementById('message');
var PATTERN = /abc/;
var REQUIREMENTS = "valid entries must contain the string 'abc'";
function match() {
txt = document.getElementById('txt').value;
if (PATTERN.test(txt)) {
enter.disabled = '';
} else {
enter.disabled = true;
}
}
function showText(option) {
message.innerHTML = option ? REQUIREMENTS : "";
}
</script>
Two problems here:
The variable txt is defined once outside the function match, so the value is fixed to whatever the input with id txt has when the script/page is loaded.
You should move var txt = $("#txt").val(); into the match function.
Notice I changed the function value() to val().
Problems identified:
jQuery events don't happen on disabled inputs: see Event on a disabled input
I can't fix jQuery, but I can simulate a disabled button without it actually being disabled. There's other hacks you could do to get around this as well, for example, by overlaying a transparent element which actually captures the hover event while the button is disabled.
Various syntactical errors: format your code and read the console messages
.hover()){ function() { ... } } is invalid. It should be .hover(function() { ... })
else doesn't need to be followed by an if if there's no condition
.hover( handlerIn, handlerOut ) actually takes 2 arguments, each of type Function
$('input[type="submit"]) is missing a close '
Problems identified by #Will
The jQuery function to get the value of selected input elements is val()
val() should be called each time since you want the latest updated value, not the value when the page first loaded
Design issues
You don't revalidate once you enable input. If I enter "abc" and then delete the "c", the submit button stays enabled
You never hide the help message after you're done hovering. It just stays there since you set the text but never remove it.
https://jsfiddle.net/Lh4r1qhv/12/
<div id="message" style="visibility: hidden;">valid entries must contain the string 'abc'</div>
<form method="POST">
<input type="text" id="txt" />
<input type="submit" id="enter" value="enter" style="color: grey;" />
</form>
<script>
var PATTERN = /abc/;
$("#enter").hover(
function() {
$("#message").css('visibility', $("#txt").val().match(PATTERN) ? 'hidden' : 'visible');
},
$.prototype.css.bind($("#message"), 'visibility', 'hidden')
);
$('form').submit(function() {
return !!$("#txt").val().match(PATTERN);
});
$('#txt').on('input', function() {
$("#enter").css('color', $("#txt").val().match(PATTERN) ? 'black' : 'grey');
});
</script>

How to apply keypress and mousedown event on dynamically created textbox

I am working in an application where i have three textboxes dynamically polulated,one is for input value 2nd one is for a time and 3 rd one is also for a time both 2nd and 3 rd boxes have timepicker api in it.So now what i need i will type something in the textbox and also select time from those two timepicker boxes and values will be appending on the respective textboxes on top of them.Like i am giving a fiddle where i have implemented the situation i have reached so far,This is it DEMO
So i will write something on textbox1 and that will be that will be showing on textbox on top of it and also i will select a time from 2 nd box and 3 rd box and that will be on the 2 nd and 3 box on top of that.I am trying to use keypress and mousedown but that is not working on dynamic population of the textboxes like i tried using
$('#TextBoxContainer').on('keypress', 'input', function () {
});
But this is not giving the value of the textboxes .Somebody please help
Try this code.
Note : I used comma to separate the values from different text boxes.
Demo
HTML
<input id="text1" type="text" value="" />
<input id="text2" type="text" value="" />
<input id="text3" type="text" value="" />
<div id="TextBoxContainer">
<input id="btnAdd" type="button" value="Add" />
</div>
JS
$(function () {
$("#btnAdd").bind("click", function () {
var div = $("<div />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
$(".time").timepicker();
$('.txt1,.txt2,.txt3').change(function () {
UpdateData()
});
});
$("#btnGet").bind("click", function () {
var valuesarr = new Array();
var phonearr = new Array();
var phonearr1 = new Array();
$("input[name=DynamicTextBox]").each(function () {
valuesarr.push($(this).val());
$('#DynamicTextBox').val(valuesarr);
});
$("input[name=phoneNum]").each(function () {
phonearr.push($(this).val());
$('#phoneNum').val(phonearr);
});
$("input[name=phoneNum1]").each(function () {
phonearr1.push($(this).val());
$('#phoneNum1').val(phonearr1);
});
alert(valuesarr);
alert(phonearr);
alert(phonearr1);
});
$("body").on("click", ".remove", function () {
$(this).closest("div").remove();
});
});
function GetDynamicTextBox(value) {
return '<input class="txt1" name = "DynamicTextBox" type="text" value = "' + value + '" /> <input class="txt2 time" id="myPicker" class="time" type="text" /> <input name = "phoneNum1" id="phoneNum1" class="time txt3" type="text" /><input type="button" value="Remove" class="remove" />';
}
function UpdateData() {
var text1 = ''
$('#TextBoxContainer').find('.txt1').each(function (index, Obj) {
if ($(Obj).val()) text1 += $(Obj).val() + ','
})
$('#text1').val(text1)
var text2 = ''
$('#TextBoxContainer').find('.txt2').each(function (index, Obj) {
if ($(Obj).val()) text2 += $(Obj).val() + ','
})
$('#text2').val(text2)
var text3 = ''
$('#TextBoxContainer').find('.txt3').each(function (index, Obj) {
if ($(Obj).val()) text3 += $(Obj).val() + ','
})
$('#text3').val(text3)
}
If I understood you correctly, you don't need processing keypress and mousedown events.
You just need to process onsubmit event of your form. Just read values from textbox, DateTimeBox, DateTimeBox and paste them to newly created textbox2, DateTimeBox21, DateTimeBox22.
In case you want to create dynamicly 3 input boxes with the value of text1 text2 and text3 here is the result.
And this is pretty much what i've changed:
...
$("#btnAdd").bind("click", function () {
var a = $("#text1");
var b = $("#text2");
var c = $("#text3");
var div = $("div");
div.html(GetDynamicTextBox(a, b , c));
...
Obviously in GetDynamicTextBox() function i'm filling the InputBoxes with the expected values (from a, b and c).
In case you want to update text1 text2 and text3 with the values of the generated input boxes this would do it:
here is the relevant code i've changed on this one:
$('.txt1').bind('keyup',function(e){
var code = e.which;
if(code==13)e.preventDefault();
if(code==32||code==13||code==188||code==186){
$('#text1').val($('#text1').val()+', '+$(this).val());
}
});
For the above solution to work, you've got to press enter after changing each input box.
In case you preffer to not press enter here you've got a solution which works when the generated input box loses the focus.
This is the relevant code:
$('.txt1').bind('focusout',function(){
$('#text1').val($('#text1').val()+', '+$(this).val());
});
You might want to check if the new value is the same that the old one or not in this one.
PS: I'm showing here the snippet of just the first inputbox since for the rest of them is pretty much the same. The complet solution is in the jsfiddle though.

Change content of a div on another page

On page 1, I have a div containing information.
<div id='information'></div>
And on page 2, I have a form with a textarea and a button.
<form>
<textarea id='new-info'></textarea>
<input type='submit' id='submit-info' value='pass'/>
</form>
Now what I want is when I click the submit button, the text inputted in the text area will be posted in div#information changing its previous content.
I have seen many other post on how to change div content, but those were unrelated to my problem.
One way is to do like what the other answers mentioned, to have each tab communicate to a central server that will get/send data to keep both tabs updated using AJAX for example.
But I'm here to tell you about another way though, it's to use what we already have designed for this kind of task exactly. What so called browser localStorage
Browser storage works like this pseudo code:
//set the value, it works as a hash map or assoc array.
localStorage .setItem("some_index_key", "some data") ;
// get the value by it's index key.
localStorage .getItem("some_index_key") ; // will get you "some data"
Where all the data will be shared among all open tabs for the same domain. And you can add event listener so whenever one value change, it will be reflected on all tabs.
addEvent(window, 'storage', function (event) {
if (event.key == 'some_index_key') {
output.innerHTML = event.newValue;
}
});
addEvent(myInputField, 'keyup', function () {
localStorage.setItem('some_index_key', this.value);
});
Check out this DEMO, you edit one field on page-A, and that value will be reflected on page-B offline without the need to burden the network.
To learn more, read this.
Real live example. The background color is controlled from another tab.
var screenone = document.getElementById('screenone');
screenone.addEventListener('keydown', screenOneFunction);
screenone.addEventListener('change', screenOneFunction);
function screenOneFunction()
{
document.body.style.backgroundColor = this.value;
localStorage.setItem("color1", this.value);
}
var screentwo = document.getElementById('screentwo');
screentwo.addEventListener('keydown', function (evt) {
localStorage.setItem("color2", this.value);
});
screentwo.addEventListener('change', function (evt) {
localStorage.setItem("color2", this.value);
});
var thebutton = document.getElementById('thebutton');
thebutton.addEventListener('click', function (evt) {
localStorage.clear();
screenone.value = "";
screentwo.value = "";
document.body.style.backgroundColor = "";
});
var storageHandler = function () {
document.body.style.backgroundColor = localStorage.color2;
var color1 = localStorage.color1;
var color2 = localStorage.color2;
screenone.value = color2;
screentwo.value = color1;
};
window.addEventListener("storage", storageHandler, false);
.screenone{ border: 1px solid black;}
input{ margin: 10px; width: 250px; height: 20px; border:round}
label{margin: 15px;}
<html>
<head>
</head>
<body>
<label> Type a color name e.g. red. Or enter a color hex code e.g. #001122 </label>
<br>
<input type="text" class="screenone" id="screenone" />
<label> This tab </label>
<br>
<input type="text" class="screentwo" id="screentwo" />
<label> Other opned tabs </label>
<br>
<input type="button" class=" " id="thebutton" value="clear" />
</body>
</html>
Hope this will give you an idea of how you can do it:
Page 2
HTML
<form>
<textarea id='new-info'></textarea>
<input type='submit' id='submit-info' value='pass'/>
</form>
JS
$("form").submit(function(e){
e.preventDefault();
$.post('save_data.php', { new_info:$("#new-info").val() }).done(function(data){
// Do something if you want to show that form has been sent
});
});
save_data.php
<?php
if (isset($_POST['new-info'])) {
// Update value in DB
}
?>
Page 1
HTML
<div id='information'>
</div>
JS
setInterval(search_after_info, 1000);
function search_after_info() {
$.get('get_data', function(data) {
$("#information").html(data);
});
}
You mean some thing like this ?
$("#submit-info").click(function() {
var content = $("#new-info").text();
$("#information").html(content);
});
If you thing about server side, tell more about technology, which you use.
This is exactly as the following:
Page 1:
<form action="test2.htm" method="get">
<textarea name ='new-info'></textarea>
<input type = 'submit' id='submit-info' value ='pass' onclick="postData();"/>
Page 2
<div id="information"></div>
<script>
if (location.search != "")
{
var x = location.search.substr(1).split(";")
for (var i=0; i<x.length; i++)
{
var y = x[i].split("=");
var DataValue = y[1];
document.getElementById("information").innerHTML = DataValue;
}
}
</script>

Previewing text using Jquery

I am creating a system where a user can preview the title and steps of a recipe, i have created a dynamic form so the user can add more steps, the preview works with the title and first step however it seems that i can't get it to work on the second, third, fourth step. Can anyone help me? Any help would be greatly appreciated!
http://jsfiddle.net/uKgG2/
Jquery
var commentNode = $('#lp-step'),
nameNode = $('#lp-name');
$('input, textarea').bind('blur keyup', function () {
commentNode.html($('textarea[name="step_detail[]"]').val().replace(/\n/g, '<br />'));
nameNode.text('Title: ' + $('input[name="name"]').val());
});
var addDiv1 = $('#addStep');
var i = $('#addStep p').size() + 1;
$('#addNewStep').on('click', function () {
$('<p> <textarea id="step_' + i + '" name="step_detail[]"> </textarea>Remove </p>').appendTo(addDiv1);
i++;
return false;
});
$(document).on('click', '.remNew1', function () {
if (i > 2) {
$(this).parents('p').remove();
i--;
}
return false;
});
HTML
<label for="name">Enter recipe name:</label>
<input type="text" name="name">
<br />
<h1>Method</h1>
<div id="addStep">
<p>
<textarea id="step_1" name="step_detail[]"></textarea>
Add
</p>
</div>
<br />
<button type="submit">
Save on xml
</button>
</form>
<div id="live-preview-display">
<div id="lp-name"> </div>
<div id="lp-step"> </div>
</div>
You should bind the keyup or blur event to all the new textareas which are created with add button or link whatever.
Improved
try this :
$('#addStep').on('keyup', 'textarea', function () {
step_id = $(this).attr('id');
step_text = $('#' + step_id).val();
if($('.'+step_id).length > 0) {
$('.'+step_id).text(step_text);
return;
}
p = document.createElement('p');
p.className = step_id;
$(p).appendTo(commentNode);
$(p).text(step_text);
});
it worked! I saved it to fiddle too. you should just update the recipe name and clean this as I said i't very hacky just have to improve it.good luck. http://jsfiddle.net/uKgG2/3/

jquery question regarding text change

<script type="text/javascript">
$(function () {
var text3;
$('.HideButton').click(function () {
text3 = $('#MessageText').text;
var theButton = $(this);
$('#disclaimer').slideToggle('slow', function () {
theButton.val($(this).is(':visible') ? 'Hide' : 'Show');
});
$('<p>' + text3 + '</p>').addClass("new").insertAfter('#disclaimer');
return false;
});
});
updated...code above doesnt change the buttons text
<p id="disclaimer" > DDDDDDDDDDDDDDDDDDDDDDDDDD</p>
<asp:Button ID="Button1" CssClass="HideButton" runat="server" Text="Hide" />
I want the text of the button to change each time i press on it..But it doesnt
<p id="disclaimer" >
<input id="MessageText" type="text" />
</p>
<asp:Button ID="Button21" CssClass="HideButton" runat="server" Text="Hide" />
As message typed in the textbox..it should appear while "#disclaimer disappear
The will render out to a form element. This means you should use .val() instead of .text()
Also as Neil has pointed out, you are returning before this gets executed.
$('.HideButton').click(function () {
$('#disclaimer').slideToggle('slow');
// return false;
if ($('#disclaimer').is(':visible')) {
$(this).val('Hide');
} else {
$(this).val('Show');
}
});
});
<p id="disclaimer" > DDDDDDDDDDDDDDDDDDDDDDDDDD</p>
<asp:Button ID="Button1" CssClass="HideButton" runat="server" Text="Hide" />
Thats because you returned before you canged any text.
remove the return ...; (or move it to the end of the function)
Try returning false at the end ;)
Your original question was answered a few different times and a couple different ways. Now you've asked what is essentially a completely new question.
I recommend any further changes be formed into their own questions.
Is this what you now want?
http://jsfiddle.net/kasdega/99GaJ/1/
After return your code will never be executed. Try this
$('.HideButton').click(function () {
var theButton = $(this);
$('#disclaimer').slideToggle('slow', function(){
theButton.val($(this).is(':visible')?'Hide':'Show');
});
return false;
});

Categories

Resources