Two way data binding using div - javascript

I am working with reactjs with redux.
i have created an editable div instead of input textfield but unable to receive the value.
So, in input textfield. There is a event named onChange which let you access the value type in input field.
For example -
handlechange(e){
console.log(e.target.value); //get the value of textbox then i further save it in state
}
render()
{
return (
<input
onChange={this.handleChange.bind(this)}
value={this.state.msgText}
</>
)}
But I am using the editable div for same like this
<div
role="textbox"
ref={function(e){if(e != null) e.contentEditable=true;}}
title="Type the text"
//onChange={this.handleChange.bind(this)}
onKeyUp={this.handleKeyUp.bind(this)}
>
{this.state.msgText}
</div>
So , in handleKeyUp function
handleKeyUp(e){
var t = this;
console.log('test');
console.log(e);
console.log(e.target.value); // I have read ,i can only receive the keycode here,cannot receive value
console.log(this.state.msgText); //So i should receive the value here but i am not
if(e.which == 13) {
e.preventDefault();
//reset the state for clear the div
t.setState({
msgText: ""
});
}
}
Once way of doing this is adding id on div like this -
<div
id={"fc-"+ this.props.thread.uid + "-textbox"}
role="textbox"
className="ifc-chat-window-textbox-input"
ref={function(e){if(e != null) e.contentEditable=true;}}
title="Type the text"
//onChange={this.handleChange.bind(this)}
//onKeyUp={this.handleKeyUp.bind(this)}
>
{this.state.msgText}
</div>
Then in componentDidMount function
componentDidMount(){
var t = this;
var node = document.getElementById("fc-"+ this.props.thread.uid + "-textbox");
var value = node.textContent; // I receive the value here
node.onkeypress = function(event){
t.setState({
msgText: node.textContent
}); });
if(event.which == 13) {
event.preventDefault();
t.sendMsgObject(value , t.props.thread.uid, t.props.thread.name, t.props.thread.color, t.props.actions, t.props.user);
//reset the state for clear input field
t.setState({
msgText: ""
});
}
All this works fine, but i dont think that is how things works in react. I am looking do to this without using id to div.

have u tried something like that ?
var handleChange = function(event){
this.setState({html: event.target.value});
}.bind(this);
return (<ContentEditable html={this.state.html} onChange={handleChange} />);
ContentEditable class
var ContentEditable = React.createClass({
render: function(){
return <div
onInput={this.emitChange}
onBlur={this.emitChange}
contentEditable
dangerouslySetInnerHTML={{__html: this.props.html}}></div>;
},
shouldComponentUpdate: function(nextProps){
return nextProps.html !== this.getDOMNode().innerHTML;
},
emitChange: function(){
var html = this.getDOMNode().innerHTML;
if (this.props.onChange && html !== this.lastHtml) {
this.props.onChange({
target: {
value: html
}
});
}
this.lastHtml = html;
}
});

Related

jQuery or javascript prevent event from input keypress

CODE:
var appender = $('<input class="form-control" placeholder="Search" id="search_made" type="text">')
appender.find('#search_made').on('keypress', function(e) {
e.preventDefault()
console.log('keypress!')
if (e.keyCode == 13 && !e.shiftKey) {
console.log('not shift enter')
var passed_value = $(this).val()
if (passed_value === '') {
console.log('nothing was passed on input tag')
return false;
}
console.log('passed value: ' + passed_value)
}
})
$('body').append(appender)
I want to add input tag dynamically by jQuery.
Using those code, I can only add input tag seemingly but other functions that has to be bound was not bound well.
So when I type some words on input tag and click enter key, It refreshes page but does not execute any console.log() lines.
How can I fix it to make it do other bound functions(include console.log()) well?
Change the selector from:
appender.find('#search_made').on('keypress', function(e) {
To
$(document).on('keypress','#search_made', function(e) {
OR: Simply
appender.on('keypress', function(e) {
Working Code Example:
var appender = $('<input class="form-control" placeholder="Search" id="search_made" type="text">')
$(document).on('keypress','#search_made', function(e) {
e.preventDefault()
console.log('keypress!')
if (e.keyCode == 13 && !e.shiftKey) {
console.log('not shift enter')
var passed_value = $(this).val()
if (passed_value === '') {
console.log('nothing was passed on input tag')
return false;
}
console.log('passed value: ' + passed_value)
}
})
$('body').append(appender)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

When user enters text in textbox then append a prefix value

I have a textbox which needs to be filled with website URL. So when user places the cursor in the textbox then the textbox should prefill with "http://" (Not a placeholder).
If the user does not enter anything and moves to the next textbox then the textbox have empty value
If the user fills the textbox then the value is unchanged
I tried below Javascript code but did not work:
if (document.activeElement.id == 'input-textbox-id' && !document.activeElement.value) {
document.querySelector("#input-textbox-id").value="http://";
} else if (document.activeElement.id != 'input-textbox-id' && (!document.activeElement.value || document.activeElement.value == 'http://')) {
document.querySelector("#input-textbox-id").value="";
}
You can use the focus and blur events for this.
Assuming that the variable textBox contains the reference to your textBox element, you can use the following code:
let textBox = document.getElementById("a");
textBox.addEventListener("focus", function() {
if (!this.value) {
this.value += "http://";
}
});
textBox.addEventListener("blur", function() {
if (this.value == "http://") {
this.value = "";
}
});
<input type="text" id="a">
You will need to attach event listener by using addEventListener. Events you need: focus and focusout.
We add .http-prefill class for all inputs. We iterate over inputs array and attach event.
Please do not forget to remove eventListener when you are done eg. you unload the form.
To do so, just copy the code for adding listeners and replace addEventListener with removeEventListener.
inputs.forEach(function(input) {
input.removeEventListener('focus', onFocus);
input.removeEventListener('focusout', onFocusOut);
});
Example code:
var fillValue = 'http://';
var onFocus = function() {
this.value = fillValue;
}
var onFocusOut = function() {
if (this.value === fillValue) {
this.value = '';
}
}
var inputs = document.querySelectorAll('.http-prefill');
inputs.forEach(function(input) {
input.addEventListener('focus', onFocus);
input.addEventListener('focusout', onFocusOut);
});
.http-prefill {
width: 100%;
margin-bottom: 5px;
}
<input class="http-prefill" name="input-0" />
<input class="http-prefill" name="input-1" />
<input class="http-prefill" name="input-2" />
<input class="http-prefill" name="input-3" />
you can use some key events like onKeyDown and when keydown you can get hold of old value and append it with new value.
let keyPressed = true
function onKeyDown(event) {
if(keyPressed && event.keyCode !== 8)
{
keyPressed = false;
let oldvalue = document.getElementById('input-textbox-id').value;
document.getElementById('input-textbox-id').value = "http://"+oldvalue
}
if(!document.getElementById('input-textbox-id').value)
{
keyPressed = true;
}
}
here is working code. http://jsbin.com/zoxiwokepi/edit?html,output

appendChild Possibly Deleting Element?

I am trying to create a simple to-do list application JavaScript. I have written up JavaScript to basically take the value from an input element and pass it into a few functions.
I created a live example on CodePen, which you may view here: http://cdpn.io/hnBmD
Edit: Code also located below?
It seems like appendChild could possibly be deleting the "li" node that the parent function is creating? May someone please give me a reasonable explanation to this?
Note: I do have the JavaScript in a separate file and it is being loaded right before the ending body tags.
HTML:
<form>
<p><input type="text" id="inItemText" autofocus><button type="submit" id="submitButton">+</button></p>
</form>
<ul id="toDoList">
</ul>
JavaScript:
// Defining nodes.
var inItemText = document.getElementById("inItemText");
var submitButton = document.getElementById("submitButton");
// Once "enter" is pressed or click event is triggered, execute the function.
// The function below is basically checking the value of the input, to make sure the value is empty. If it isn't, it passes the value and the "ul" element node into the addNewItem function.
submitButton.onclick = function(){
var itemText = inItemText.value;
if (itemText == "" || itemText == " ") {
return false;
} else {
addNewItem(document.getElementById("toDoList"), itemText);
}
}
// Once the parameters are passed. This basically creates a "li" element, applies the value of the input element into the innerText of the "li" element created and then appends the "ul" with the "li" we just created. Also, it resets the value of the input so we can enter another checklist item in.
function addNewItem(list, itemText) {
var listItem = document.createElement("li");
listItem.innerText = itemText;
list.appendChild(listItem);
itemText = inItemText.value = "";
}
Thank you!
You need to return false from the onclick function after it calls addNewItem. Otherwise it will submit the form, which reloads the page.
submitButton.onclick = function(){
var itemText = inItemText.value;
if (itemText == "" || itemText == " ") {
return false;
} else {
addNewItem(document.getElementById("toDoList"), itemText);
return false;
}
}
DEMO
Or more simply:
submitButton.onclick = function(){
var itemText = inItemText.value.trim();
if (itemText !== "" || itemText == " ") {
addNewItem(document.getElementById("toDoList"), itemText);
}
return false;
}
Or, as one of the comments suggested, get rid of the form, then there's nothing to submit.
Remove the form if not necessary or just prevent the default form submit action.
submitButton.onclick = function (e) {
e.preventDefault();
var itemText = inItemText.value;
if (itemText == "" || itemText == " ") {
return false;
} else {
addNewItem(document.getElementById("toDoList"), itemText);
}
}
The button element in your HTML has a type attribute of submit. When its click event is triggered, the default action is performed which is to submit the form. You need to prevent this default behaviour.
var inItemText = document.getElementById("inItemText");
var submitButton = document.getElementById("submitButton");
submitButton.onclick = function(e){
e.preventDefault(); //prevent it from submitting
var itemText = inItemText.value;
if (itemText == "" || itemText == " ") {
return false;
} else {
addNewItem(document.getElementById("toDoList"), itemText);
}
}
function addNewItem(list, itemText) {
var listItem = document.createElement("li");
listItem.innerText = itemText;
list.appendChild(listItem);
}

Javascript on input text change, change div text

I am trying to change text of one div, when I enter different values into my text input:
EXAMPLE:
Input = 1,
DIV TEXT: "rok" //in eng. "year"
Input = 2,
DIV TEXT: "roky"
Input = 3,
DIV TEXT: "roky"
Input = 4,
DIV TEXT: "roky"
Input = 5,
DIV TEXT: "rokov"
Default value of my input is 3.
html
<input type="text" id="pocetrokov" value="3"><span id="year">roky</span>
Js:
function rok() {
if(roky==2 || roky==3 || roky==4){
$('#year').html('roky');
} else if( roky>4 || roky == 0){
$('#year').html('rokov');
} else if (roky==1){
$('#year').html('rok');
}
}
$(function () {
$('select, input').on('keydown blur change', rok);
});
I get this when I change the defalut value:
Input = 1,
DIV TEXT ="rokov" instead of "rok"
Input = 2,
DIV TEXT ="rokov" instead of "rok"
... etc.
I get the correct value only when I click somehere outside the input
What is wrong?
Thank you.
Try this:
function rok(roky) {
if(roky==2 || roky==3 || roky==4){
$('#year').html('roky');
} else if( roky>4 || roky == 0){
$('#year').html('rokov');
} else if (roky==1){
$('#year').html('rok');
}
}
$(function () {
$('input').on('keyup blur change', function(){
rok( $(this).val() );
});
});
Use Keyup Event instead of other,because value of text field is fetched when you keydown and when key down your actual value thats on variable is the previous value,Not the one that is currently in input field So, the function Works correctly :
$(function () {
$('input').on('keyup', rok);
});
Here is DEMO
Guys why are you complicating it so much with 2 functions?
$("html").on("keyup","#pocetrokov",function(){
var roky=parseInt($(this).val());
if(roky==2 || roky==3 || roky==4){ $('#year').html('roky');}
else if(roky>4 || roky === 0) { $('#year').html('rokov');}
else if (roky==1){ $('#year').html('rok'); }
});

Javascript: programmatically change onfocus function

I have several text boxes that can auto-fill with data and I am using a javascript function to clear the text box one time, then revert to a javascript function that only clears when certain text is input.
For instance: A text box with standard input as "ADDRESS" will be auto-filled with "ABC123" then onfocus be cleared. If the text box remains empty, then onblur, it will return to "ADDRESS"
This is similar to the question at Change an element's onfocus handler with Javascript? but I couldn't get it to work. Any suggestions?
My text boxes are just ASP.NET text boxes and the onfocus/onblur events are set in the code behind:
<asp:TextBox ID="txtAddress" Text="ADDRESS" runat="server" CssClass="txtboxwrong" />
Code Behind:
txtAddress.Attributes.Add("onFocus", "clearOnce(this,'ADDRESS');")
txtAddress.Attributes.Add("onBlur", "restoreText(this,'ADDRESS');")
My javascript is as follows:
function clearText(obj, deftext, defclass, defvalue) {
if (obj.value == deftext) {
if (!defvalue) { defvalue = '' }
obj.value = defvalue;
if (!defclass) { defclass = 'txtbox' }
obj.className = defclass;
}
};
function restoreText(obj, deftext, defclass, defvalue) {
if (!defvalue) { defvalue = '' }
if (obj.value == defvalue || obj.value == '') {
obj.value = deftext;
if (!defclass) { defclass = 'txtboxwrong' }
obj.className = defclass;
}
};
function clearOnce(obj, deftext) {
obj.value = '';
obj.className = 'txtbox';
obj.onfocus = function () { clearText(obj, deftext); };
};
EDIT:
Thanks to #rescuecreative, I have fixed the probem. By returning the onfocus change in clearOnce, it sets the element's onfocus to the right function and works properly! Edit below:
function clearOnce(obj, deftext) {
obj.value = '';
obj.className = 'txtbox';
return function () { clearText(obj, deftext); };
};
Can your asp textbox use the placeholder attribute? In html5, the placeholder attribute automatically creates the exact functionality you're looking for.
<input type="text" placeholder="ADDRESS" />
The above text field will show the word "ADDRESS" until focused at which point it will empty out and allow the user to type. If the user leaves the field and it remains empty, the placeholder reappears. If you can't depend on html5, there is a JavaScript plugin that will create that functionality in browsers that don't support it natively.
It seems like you wanted to do something similler to watermarks. You can achiever it in much simpler way. Try this.
function clearOnce(obj, deftext) {
if(obj.value == deftext) {
obj.value = '';
obj.className = 'txtbox';
}
}
function restoreText(obj, deftext) {
if(obj.value == '') {
obj.value = deftext;
obj.className = 'txtboxwrong';
}
}
Ideally you would just use the placeholder attribute, but that may not be supported on older browsers. If you can use jQuery, something like this would work for you:
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur();
If nothing is ever entered into the field, the code below will ensure the placeholder text doesn't get submitted with the form:
$('[placeholder]').parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});

Categories

Resources